.htaccess - preventing infinite loops with URL rewriting

669 views Asked by At

I have a .htaccess that contains the following :

<Files .htaccess>
order allow,deny
deny from all
</Files>

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(.*)/maintenance/(.*)$ [NC]

RewriteRule ^(.*).jpg$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteRule ^(.*).jpeg$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteRule ^(.*).gif$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteRule ^(.*).png$ /mysite/maintenance/transparent.png [NC,R=302,L]

RewriteRule ^(.*).php$ /mysite/maintenance/maintenance.php [NC,R=302,L]

Tested on localhost.

With these settings, I have an infinite loop when trying to load http://localhost/mysite/test.php, (correctly) redirected to http://localhost/mysite/maintenance/maintenance.php

The loop seems to be due to the 4 image redirection (note : the maintenance page has a one an unique jpg background image located in the maintenance folder root). Commenting these 4 redirection lines solves the problem.

But I don't see why I enter in an infinite loop as the /maintenance/ path is itself excluded from redirection in the RewriteCond, and why the redirection on the images can interfere with this problem.

Can you help ?

2

There are 2 answers

2
umka On BEST ANSWER

You have to reorder your RewriteConds like this:

RewriteEngine On

RewriteRule \.jpg$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteRule \.jpeg$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteRule \.gif$ /mysite/maintenance/transparent.png [NC,R=302,L]
RewriteCond %{REQUEST_URI} !^.*/maintenance/.*$ [NC]
RewriteRule \.png$ /mysite/maintenance/transparent.png [NC,R=302,L]

RewriteCond %{REQUEST_URI} !^.*/maintenance/.*$ [NC]
RewriteRule \.php$ /mysite/maintenance/maintenance.php [NC,R=302,L]

RewriteCond directive affects only the first RewriteRule after it.

0
Mike Rockétt On

I know the answer for this has been accepted, but there is a shorter method that can be used here:

RewriteEngine On

RewriteRule \.(jpe?g|gif)$ /mysite/maintenance/transparent.png [NC,R=302,L]

RewriteCond %{REQUEST_URI} !/maintenance/ [NC]
RewriteRule \.(png|php)$ /mysite/maintenance/transparent.$1 [NC,R=302,L]