The hell that is mod_rewrite infinity!

Geplaatst in PHP, Webdevelopment Nog geen reacties op dit bericht

Apache’s Mod_rewrite module has always been a difficult part of webdevelopment for me, wether it is because of it’s extensive use of regular expressions (which I finally master after several years of staring at regex tutorials) or the lack of response you get when something goes wrong. At work we use mod_rewrite on almost each project thus having a stable and solid base of rules to start from is a must.

Recently we decided it was time to implement something new with mod_rewrite i’ve been thinking about for a long time. Rewritten URLs with unlimited parameters by Ruben K. This allows me to rewrite a long and complex request URL into as many $_GET variables I need by using a simple PHP function. I’m not going to discuss the details here since thats something the tutorial by Ruben K. already does but let me tell you one thing … Ruben forgot something.

On a recent project I noticed that the debugger instance I was running in index.php got called several times while I only requested the page once. Strange no? The cause was quickly found … mod_rewrite! Finding the solutions took me weeks …

This rule is suggested by Rubens tutorial

RewriteRule ^(.*)\.html$ index.php?string=$1

The problem here is that ANYTHING gets rewritten to index.php … including broken images and other includes that should normally trigger a 404. Well “just fix your broken images” you’d say and yes you are right, but there are 2 problems with that. We can’t count on our client inserting only valid image links in our CMS. And second, firefox and other browsers have a habit of requesting favicon.ico several times during the loading of a page and guess what … if you don’t have a favicon it gets rewritten to index.php too!

I don’t need to tell you that this results in serious overload. I tried the modrewrite.com and sitepoint.com forums but nobody could give me a solid solutions until I found it myself. With a simple rewrite condition we are going to check if the url requested is a file that is not found and if so we rewrite to an error page. The final .htaccess looks like this, with the newly added rule in bold:

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} -f [OR]
RewriteCond %{SCRIPT_FILENAME} -d
RewriteRule .* - [L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.+)\.[a-zA-Z0-9]{3,}$ /error.php [L]

RewriteRule ^(.*)$ /index.php?string=$1 [L]

This fixed alot of problems we previously had with several sites and never knew where to look … mod_rewrite was to blame.


Reacties

Er zijn nog geen reacties op dit bericht

Reageer

XHTML: Je mag volgende XHTML tags gebruiken: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>