How to block multiple mod_rewrite passes (or infinite loops) in a .htaccess context

后端 未结 3 1725
清酒与你
清酒与你 2020-12-08 11:14

I\'m working on a website running on a shared Apache v2.2 server, so all configuration is via .htaccess files, and I wanted to use mod_rewrite to map URLs to the filesystem

相关标签:
3条回答
  • 2020-12-08 11:44

    Variables set by RewriteRule (that one that modified path) are available on "next round" ("internal redirect") with prefix REDIRECT_ prepanded. So your first code snippet should look this way:

    RewriteCond %{ENV:REDIRECT_END} =1
    RewriteRule .* - [L]
    

    This works for me with apache 2.4.10.

    0 讨论(0)
  • 2020-12-08 11:46

    Depending on your Apache build, this condition may work (add it to "stop-rewriting" rule: i.e. RewriteRule .* - [L] .. or just for specific problematic rule):

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    

    REDIRECT_STATUS will be empty of very first / initial rewrite and will have value of 200 (or maybe other value as well -- have not checked that deep) on any subsequent cycle.

    Unfortunately it works on some systems and does not on others and I personally have no idea what is responsible for making it working.

    Other than this the most common thing is to add rewrite condition to check the original URL, for example by parsing %{THE_REQUEST} variable e.g. RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+ -- but this only makes sense for individual problematic rules.

    In general -- you should avoid such "rewrite A -> B and then B -> A" situations (I'm pretty sure you are aware of that).

    As for your own solution -- "don't fix if it ain't broken" -- if it works then it's great as I do not see any major problems with such approach.

    0 讨论(0)
  • 2020-12-08 12:03

    I'm not too sure why you need to do that, but I'd suggest a couple of things for users who run in such a situation:

    1. How about renaming the folder Bob into Alice and vice versa? Then Apache doesn't need to do anything about them.

    2. If that's important for your application, could you just transform the app. to detect Bob and Alice and just swap those in your app. instead?

    In PHP it would be something like this:

    if($path == "Bob") {
      $path = "Alice";
    }
    else if($path == "Alice") {
      $path = "Bob";
    }
    

    Done.

    Otherwise adding another sub-folder could be useful. So /Bob becomes /a/Alice and /Alice becomes /b/Bob. Then you remove the confusion. That could also be done with another parameter (query string), which is more or less what you're doing by setting an environment variable that you test in your .htaccess.

    0 讨论(0)
提交回复
热议问题