apache.htaccessmod-rewriteurl-rewriting

Using RewriteCond with %{REQUEST_URI} for mod_rewrite


I would like the URL:

http://example.net/category/subcategory/title

To point to:

http://example.net/posts/category/subcategory/title.php

My .htaccess file looks like this:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} !^.+
#RewriteCond post/%{REQUEST_URI}.php -f
RewriteRule ^(.*)$ post/$1.php [L]

This works. However, when I uncomment the line with "post/" and "REQUEST_URI" above, it does not work.

I have tried:

RewriteCond /post/%{REQUEST_URI}.php -f
RewriteCond post/%{REQUEST_URI}.php -f
RewriteCond post%{REQUEST_URI}.php -f

None of these work. What am I doing wrong?

Also, is there an easy way to debug these rules? Like console logging variables or something?


Solution

  • The -f check requires a full file system path. You can do this using the %{DOCUMENT_ROOT} variable:

    RewriteEngine on
    RewriteBase /
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{QUERY_STRING} ^$
    RewriteCond %{DOCUMENT_ROOT}/post/$1.php -f
    RewriteRule ^(.+)$ post/$1.php [L]