Sep
03

Mod_rewrite magic several things to consider

03 Sep 2009 by tonie in Linux

Yes, it is definitely a voodoo, powerful and beautiful, but still a voodoo. There are several things I had to learn the hard way before I got the hang of Apache's URL rewriting module - mostly trial and error (some stuff I couldn't even suppose existed). Anyways :

Never copy - paste rewrite rules and expect them to work on your machine - that is to say Do not do dull copy-pasting. Always, copy and paste after you are 100% positive you have understood the code and it makes crystal clear sense to you.

Try to use canonical URLs in your HTML markup. This will save you trouble when you switch the RewriteEngine on Tongue out.

If you have already written 15 PHP pages, 1500 lines each and you used relative linking to images, JS files, etc, try putting a <base href="http://yourwebsite.com/" /> in the <head> of your document, before undertaking the botlike task of fixing all those links Tongue out

Do not make your .htaccess file a "2k lines of bullshit" type of file. mod_rewrite only goes so far and then it becomes a burden (you also increase the chance of an error, which you can't spot at the moment). Put several rules in there and then let your scripts handle the rest.

Mod rewrite isn't only used for creating pretty links. Figure out how you can harness it to do your dirty redirects or maybe prevent people from hotlinking to ye and stealing your bandwidth. Hint: you can ask it to replace your broken images with a stock image (remember to ask politely Smile). This is especially useful if you run an on-line store or some site with a lot of little sniffing images around.

Hope this gives you the general picture.
Use Google with caution.

Tagged as: apache, mod_rewrite, regexp, htaccess

Speak your mind ( 0 Comments)

If you liked the article and want to contribute to it, please feel free to leave your comment. HTML tags are not allowed, but you can use the following BBCode to enhance your message: [url] [quote] [code] [b] [i] [u] [color].