RewriteRule checking file in rewriten file path exists

RewriteRule ^pages/([^/\.]+) cache/pages/$1.html [NC,QSA]

# At this point, we would have already re-written pages/4 to cache/pages/4.html
RewriteCond %{REQUEST_FILENAME} !-f

# If the above RewriteCond succeeded, we don't have a cache, so rewrite to 
# the pages.php URI, otherwise we fall off the end and go with the
# cache/pages/4.html
RewriteRule ^cache/pages/([^/\.]+).html pages.php?p=$1 [NC,QSA,L]

Turning off MultiViews is crucial (if you have them enabled) as well.

Options -MultiViews

Otherwise the initial request (/pages/…) will get automatically converted to /pages.php before mod_rewrite kicks in. You can also just rename pages.php to something else (and update the last rewrite rule as well) to avoid the MultiViews conflict.

Edit: I initially included RewriteCond ... !-d but it is extraneous.

Leave a Comment