How to debug htaccess rewrite script

I was wondering how to create and debug this kind of script that can become a bit of headache if you are not used to write them (like me).

Do you use tool to create them?

Any tips to debug what's going on instead of just create a local structure and see what's happening in the browser?


Solution 1:

Note to readers: the old answer doesn't work anymore.

As of version 2.4, Apache no longer allows the RewriteLogLevel and RewriteLog directives. Now they're all bundled with the single LogLevel directive (see Log Files documentation), which supports module-specific log levels with prefixes and trace[1-8] constants. To set the highest level of logging specifically for the rewrite module, you now use the following:

LogLevel warn rewrite:trace8

Solution 2:

  1. You can use any regex testing tool to help you testing your patterns against URLs (I'm using "The Regex Coach" -- Windows app). This will only help you with pattern -- you should already know the general logic / flow of how rewrite works.

  2. To DEBUG you must be able to edit Apache config file -- use RewriteLogLevel 9 and RewriteLog /path/to/rewrite.log to see exact details on what is going on during URL rewriting (because it's a server config you will have to restart Apache to have new server config applied).

    You need level 9 if you want to debug problematic rule. Level 3 or any other pretty low value will only show you overview on what is going on without going into details.

    Do not use level 9 on busy/production server as it may generate huge log within few seconds.

  3. If you need to do 301 (permanent) redirects -- do 302 instead during a testing period (until you are happy with the rule and results -- then change to 301) as modern browsers do cache 301 redirects .. so you may end up in frustrating situation when you have completely changed the rule (or even deleted it) but browser still does the redirects. The only cure in such cases: -- clear the browser cache and reload the page.

Solution 3:

You can set RewriteLog directive in your virtualhost configuration It will write necessary info to the file specified by you.

RewriteLog "/usr/local/var/apache/logs/rewrite.log"

Further, use RewriteLogLevel directive to control the amount of logging

RewriteLogLevel 3

read through