Differences between RewriteRule in .htaccess and httpd.conf

Posted by Max Dunn Fri, 12 Jan 2007 23:08:00 GMT

This is probably obvious to people who know Apache well, but I just spent a half day struggling with the differences between RewriteRule in .htaccess and httpd.conf. I was assuming they would behave the same way, but there are slight differences:

Differences

httpd.conf

  • The request URI will have a leading slash
  • The leading slash needs to remain to find cached files
  • When using -f or !-f, it needs to have the document root on front

.htaccess

  • The request URI won’t have a leading slash
  • Can’t have a leading slash to find cached files
  • When using -f or !-f, don’t use the document root

Examples

Here is an example that looks in the public/cache directory for cached files:

httpd.conf

RewriteRule ^/$ /cache/index.html [QSA]
RewriteRule ^/([^.]+)$ /cache/$1.html [QSA]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

.htaccess

RewriteRule ^$ cache/index.html [QSA]
RewriteRule ^([^.]+)$ cache/$1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

Rails

Just to complete this example, add this line to a before_filter method in application.rb to have Rails cache files to this directory:

ApplicationController::page_cache_directory = "#{RAILS_ROOT}/public/cache"

Posted in ,  | 8 comments

Comments

  1. Gregory said 236 days later:

    Thanks for the tip! That’s very useful to know.

  2. Brian Adkins said 248 days later:

    Man, I wish I read this an hour ago! Thanks for the info.

  3. Peter said 338 days later:

    Yep works good. Just spent 2 hours trying to figure out this issue!

  4. Greg said 438 days later:

    Thanks much! Fixed my problem!

  5. Michael Houghton said 573 days later:

    Useful – I reckoned the matches would be different but you’ve still saved me an hour or two hunting down this information.

  6. Mark Sennott said 601 days later:

    I would add that query strings (the part after the ? in a URL) is part of the URI for matching purposes in .htaccess, but gets stripped off for httpd.conf rules.

  7. frederic sidler said 825 days later:

    lost also one hour with rewrite logs to try to understand ;-) thank you very much for the tip

  8. Kevin said 1143 days later:

    Wow, awesome tips – I spent to long before finding this explanation ;) No, everything works in httpd.conf!

(leave url/email »)

   Comment Markup Help Preview comment