Apache RewriteRule in .htaccess removes directory prefix

Here’s an important part Apache’s RewriteRule documentation that I didn’t read carefully enough:

— begin snip from mod_rewrite doc (near the bottom) —

Note: Pattern matching in per-directory context

Never forget that Pattern is applied to a complete URL in per-server configuration files. However, in per-directory configuration files, the per-directory prefix (which always is the same for a specific directory) is automatically removed for the pattern matching and automatically added after the substitution has been done.

— end snip from mod_rewrite doc —

So say that you’re (hypothetically) trying to rewrite something like:

http://www.somedomainname.com/teens-kids-camp/
- to -

http://www.somedomainname.com/teens-kids-camp/locations-dates/

You can accomplish this by adding this per-server RewriteRule in the httpd.conf file:

RewriteRule /teens-kids-camp/$ /teens-kids-camp/locations-dates/ [R=301,L]

However, this will not work when placed into the per-directory .htaccess file that sits in the root directory.  As mentioned in the documentation, the directory prefix is removed so that the URI you’re matching against now becomes ‘teens-kids-camp/’ instead of ‘/teens-kids/camp/’.   In order to accomplish the rewrite in the .htaccess file, the rule should be:

RewriteRule ^teens-kids-camp/$ /teens-kids-camp/locations-dates/ [R=301,L]

One Response to “Apache RewriteRule in .htaccess removes directory prefix”

  1. Chi-Ming C. says:

    Thanks Bruce for writing this up (and figuring it out for our client).

Leave a Reply