Posts Tagged ‘rewritecond’

How to avoid looping in mod_rewrite redirection

Tuesday, June 30th, 2009

When redirecting things to a new location that fits the original rewrite pattern, you end up with a recursive feedback loop and all you get is an error. If you specified a URL scheme and a domain in your rewrite (meaning that the redirection is visible to the browser) you’ll see the error in your browser saying something along the lines of “the page tried to redirect too many times”. Otherwise, the redirection will be internal, and you’ll get your server’s 500 Internal Server Error page.

redirect_loop_safari

So, how do you avoid it? Well, say you wanted to redirect some regex (regular expression) pattern to the your index page, say index.php, but it turns out that “index.php” actually matches your pattern, so index.php redirects to index.php which redirects to index.php, and so on, and so forth.

To prevent this, simply add a RewriteCond that checks the REQUEST_URI to make sure it doesn’t match the string that you redirect to. The following is an example.

RewriteCond %{REQUEST_URI} !^/?index.php$
RewriteRule ^(regex|goes|here)$ /index.php

Just make sure the regex in the first part does not match any of the pages you want to redirect, and that’s it! You’re done.

Best of luck on getting this to work the way you want it to, and happy web developing!