PHP Developer / Blog

April
6th, 2008

Figuring out why mod_rewrite isn’t working (like you expect)

Digg this article · Save to del.icio.us · Stumble it!

So you’ve set up all your rewrite rules and then sometime noticed that some of your urls aren’t working like you’d hoped. Maybe it’s throwing a 404 error or going to a different page that you’re expecting. It’s nearly impossible to track down unless you know about Apache’s RewriteLogLevel and RewriteLog directives. These gems can tell you precisely what Apache is doing when applying rewrite rules to a given request.

NOTE: If you’re getting an internal server error then check your Apache error log to see what the problem is before following the suggestions below.

Getting Apache to log mod_rewrite activity
To set these directives you’ll need access to httpd.conf or to your virtual host configuration file. While you can define rewrite rules in .htaccess you can’t put RewriteLogLevel or RewriteLog there. RewriteLogLevel is set to a number between 0 and 9. 0 means that nothing will be logged and 9 means virtually everything will be. I recommend setting it at 3 for debugging purposes and going from there. RewriteLog just takes a path to where you want the rewrite log to be saved. Just make sure that the user Apache is running as has write access to the file you specify.

RewriteLogLevel 3
RewriteLog "/path/to/your/rewrite/log"

Once you add this you’ll need to restart apache. The syntax varies based on what operating system your using but in Gentoo you can do this:

user: sudo /etc/init.d/apache2 checkconfig
Syntax Ok
user: sudo /etc/init.d/apache2 restart

Apache should now be logging rewrite information. I suggest tailing the rewrite log and making requests one at a time.

user: tail -f /path/to/your/rewrite/log

I suggest doing this on a low traffic server like a development one else it will be too difficult to track down your problem. If you don’t have access to a low traffic server then you can always use grep in conjunction with tail.

user: tail -f /path/to/your/rewrite/log | grep "some_pattern"

This should help you identify exactly what the problem is. You’ll most likely notice that it’s not hitting the rewrite rule you were expecting. Generally this happens because the rewrite rule is incorrect or a different rule above the one you expect is matching the request.

Additional resources

As always…comments welcome.

Leave a Reply

Captcha
Enter the letters you see above.


About this site:
This is my (Jaisen Mathai) personal site for potential employers who want to see my resume or portfolio. My ideal job would be to work as a PHP developer on a large scale consumer website. My experience is in using PHP, MySQL, Ajax and JSON. I really enjoy creative brainstorming...taking a problem apart and narrowing 100 solutions down to the best one.

Thanks for stopping by. Be sure to drop me a line.