10

I have the following htaccess rewrite rules. The one rule condition to prevent looping was originally written this way:

RewriteCond %{ENV:REDIRECT_STATUS} ^.

It used to work just fine, until it suddenly stopped working causing Apache to display the directory listing of the website.

I had to change it to this new form, as in the listing below, to have it work again:

RewriteCond %{ENV:REDIRECT_STATUS} 200

Do you have any idea of the reason of this behaviour?

Thank you

RewriteEngine on
RewriteBase /

## Permanent 301

## Force to www. Un-comment in production.
RewriteCond %{HTTP_HOST} !^www\.myhost\.com [NC]
RewriteRule ^(.*) http://www.myhost.com/$1 [L,R=301]

## Permanent redirect rules for contents

RewriteRule ^argument/programming/?$ tags/programming [NC,L,R=301]

## Internal Redirect Loop Protection
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

## Maintenance page
#RewriteRule (.*) special/maintenance.html

## Specials
RewriteRule special/(.*) special/$1 [NC,L]

## Static resources
RewriteRule ^(.*\.(js|ico|gif|jpg|png|css|rss|xml|htm|html|pdf|zip|gz|txt))$ public/$1 [NC,L]

## Front Controller
RewriteRule ^(.*) public/index.php [NC,L]
anubhava
  • 761,203
  • 64
  • 569
  • 643
Timido
  • 1,646
  • 2
  • 13
  • 16

1 Answers1

8

You have this condition to stop looping:

## Internal Redirect Loop Protection
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

This works by checking internal Apache variable %{ENV:REDIRECT_STATUS}. This variable is empty at the start of rewrite module but is set to 200 when first successful internal rewrite happens. This above condition says bail out of further rewrites after first successful rewrite and stops looping.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • How is it different from the one I had at start? that is: `RewriteCond %{ENV:REDIRECT_STATUS} ^.` – Timido Jan 05 '14 at 16:26
  • See your condition `RewriteCond %{ENV:REDIRECT_STATUS} ^.` will match whenever `%{ENV:REDIRECT_STATUS}` is non-empty, without making sure it is 200 (success). – anubhava Jan 05 '14 at 16:52
  • `%{ENV:REDIRECT_STATUS}` gets set for other cases as well by mod_dir, ErrorDocument etc. – anubhava Jan 05 '14 at 17:11
  • 1
    What values does the `%{ENV:REDIRECT_STATUS}` get for `[R]` and `ErrorDocument`? – Qwerty May 26 '14 at 20:56
  • 1
    So it gets the error code as value, haha. But there isn't any value for a redirect, sadly. – Qwerty May 26 '14 at 21:54
  • 1
    Yes this variable is filled only when internal rewrite happens. – anubhava May 27 '14 at 04:44