Subscribe RSS

Tag-Archive for "rewrite"

ModRewrite: File existance check Jul 01

We have written about mod_rewrite before, but did you know that you can check if a file (or directory) exists before you attempt to redirect to it? Here’s how:

RewriteCond %{DOCUMENT_ROOT}/files/%{REQUEST_URI} -f
RewriteRule ^/([^/]*)$ /files/$1 [PT]

The RewriteCond checks for the existance of a file in the specified path, this is done with the special mod_rewrite rule -f. If you want to check if a file does not exist, you could use the following:

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-f

Also, you can check for the existance of a directory with ‘-d’

The results of the above rule will allow the user, when they visit the URL

http://example.com/foo.html

to instead be served:

http://example.com/files/foo.html

so long as /files/foo.html exists. If it doesn’t, the usual behaviour will occur (such as other rewrites/redirects running, or causing a 404 error to be displayed).

Rewriting the Query String Apr 21

Sometimes you want to redirect the user to a new page based on a specific query string value. Heres  how to do that:


RewriteCond %{QUERY_STRING} foo=bar&bim=bam
RewriteRule ^horrible.php$ /farbetter.html? [R=302]

This redirects all traffic going to “horrible.php?foo=bar&bim=bam” to goto “farbetter.html”. Note that for all other querystring vars horrible.php is still available.