Apache Redirect vs RewritePosted by Jason Hawkins / November 11, 2008
How to Redirect
Nicki mentioned redirects this morning and that started me thinking (light strains of banjo). There are many ways to change the destination of a URL to another URL depending on language and access to the web server. Let’s look at the implications of some of these methods.
window.location = "http://someother.place.on.the.internet/index.html";
PHP has a method that involves manipulating the headers of the page (the raw HTTP header) – before the rest of the content loads:
header(" Location: http://someother.place.on.the.internet/index.html");
Now we have a fairly seamless redirect, but it really exacerbates any php errors/spaces that exist in the code.
Don’t forget the web hacks ye olde methode:
<meta http-equiv="refresh" content="0;url=http://someother.place.on.the.internet/index.html"/>
Which jumps you to another site as soon as the page has loaded, and if you are silly enough to hit your back button it will jump you forward again. It has the merit of being probably the simplest way to redirect.
The question here is to redirect or not to redirect. I personally prefer doing any manipulation of the URL within the webserver itself; I also understand that in shared hosting environments this is not always possible.
Apache has the ability (via mod_alias) to manipulate the raw http headers ( well duh!):
Redirect permanent index.hml http://someother.place.on.the.internet/index.html
You could also use mod_rewrite;
RedirectMatch ^/index.html$ http://someother.place.on.the.internet/index.html
OK, so what are the pro’s and cons here:
Both, of these modules do so much more, and to my mind, mod_rewrite is freakin’ awesome(!!!), but overkill.
So, it looks like mod_alias is the sensible choice for this type of redirect, especially if it is a file-to-file redirect (or folder-to-folder).
But if you were trying to redirect any page or link for the entire site somewhere else then mod_rewrite is king.
RedirectMatch ^/$ http://someother.place.on.the.internet/
So, it’s the usual case of knowing what options not to use.
Don’t forget, you can use these in your virtual host containers or use a .htaccess ( I think this is what word press does when you mess with permalinks) . Which, to a certain degree can get around the shared hosting configuration problem.
Ron Carnell in this blog raises a great point about the fact that a .htaccess file is read every time the page is loaded but httpd.conf settings are loaded only once at the server start. If you are in a high performance environment this could make a real difference to server load.