Posts Tagged ‘mod rewrite’

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!

A subdomain for each directory with .htaccess and some mod_rewrite wizardry

Wednesday, June 10th, 2009

I don’t know how useful this will be to anyone, but I was playing around with my webserver a while back and because subdomains are pretty cool I thought I would figure out for myself how to do this.

You may use either httpd.conf or an .htaccess at your document root.

Make sure you have mod_rewrite turned on before you begin.
RewriteEngine On

First, use a RewriteCond like this to prevent redirection things like your favicon.ico that need to be available everywhere. Change this based on your setup.
RewriteCond %{REQUEST_URI} !^/(favicon.ico|images/.+|javascript/.*)$

Then, capture the subdomain in %1.
RewriteCond %{HTTP_HOST} ^(.+)\..+\..+$
This next line just prevents looping by making sure the REQUEST_URI doesn’t match the what’s in %1. Don’t ask how it works.
RewriteCond %1,%{REQUEST_URI} !(^[^,]+),/\1.*

This checks to see if what we have in %1 is in fact a directory under the document root.
RewriteCond /your/document/root/%1 -d

And finally, redirect ‘/anything’ to ‘/subdomain/anything’.
RewriteRule ^(.*)$ /%1/$1 [L]

And there we go, that should do it. All together, that’s:
RewriteCond %{REQUEST_URI} !^/(favicon.ico|images/.+|javascript/.*)$
RewriteCond %{HTTP_HOST} ^(.+)\..+\..+$
RewriteCond %1,%{REQUEST_URI} !(^[^,]+),/\1.*
RewriteCond /your/document/root/%1 -d
RewriteRule ^(.*)$ /%1/$1 [L]

Questions, comments, criticism, and other feedback are very welcome. If you have a better way of doing it, let me know!