mod_rewrite
Posted on Monday, August 19 @ 19:26:51 PDT by DrFooMod2
|
|
I posted the information contained in the last article on www.nukeforums.com, and one the administrators liked it so much, he has asked for more in regards to mod_rewrite.
mod_rewrite is probably one of the better features in Apache. I can tell you that I often miss it when working w/ IIS. I know, the only parallel that you can draw between Apache and IIS is that they are both webservers, but this not an Apache v. IIS discussion. So, anyhow, this is what I've found.
First off, mod_rewrite can do an awfull lot. For example, if you want to prevent hotlinking of images on your site, an .htaccess file might look like this:
RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://www.codenoevil.com [NC] RewriteCond %{HTTP_REFERER} !^http://www.codenoevil.com [NC] RewriteCond %{HTTP_REFERER} !^http://www.anothersite.com/ [NC] RewriteCond %{HTTP_REFERER} !^http://anothersite.com/ [NC] RewriteRule /* http://www.codenoevil.com [R,L]
What this is doing is checking to see if the HTTP Referrer header is your site, which let's mod_rewrite know that the request for the file came from a page on your site. Here's another example of how usefull mod_rewrite can be. I changed the directory structure on www.analogousmember.com (my weblog), and to make sure that no one's links, especially the ones on Google, wouldn't break, I dropped this into a .htaccess file in the root:
RewriteEngine on RewriteRule ^mt/(.*)$ /$1 [R=permanent,L] RewriteRule (.*)_archive.shtml$ /archives/week_$1.shtml
This actually serves two purposed. First off, it takes any request for files under mt/ and redirects the browser to request them from / (the root) instead. Also, when I moved from blogger.com to MoveableType, the filenames were different for archive pages. So, with the help of Regular Expressions, I am able to recreate a new path based on data I plucked from the originally requested file.
Now, if you notice, the end of each rule is different. The reason for this is purely self serving on my part. The first one sends a 302, or permanent redirect, to the browser with the new path. The second just serves the different file without the direct. The reason I don't want the browser to request the different file is so I can see my Google page rank on the Google Toolbar.
There are some really good sources of information in regards to mod_rewrite on the web. Here are some links:
and of course do a Google search too.
I do have one word of note, you will see a rule that looks like this:
RewriteRule ^/$ /e/www/ [R]
This DOES NOT WORK. This does:
RewriteRule ^$ /e/www/ [R]
This caused alot of grief on my part. Just drop the / between the ^ and $ and you'll be good to go.
:)
|
| |
 |
|
Article Rating |
|
Average Score: 0 Votes: 0
|
 |
|