4

I'm trying to create a url handler by using php and .htaccess, my problem is that I don't know how to use rewrite condition only if the file\directory entered in the url does not exists.

2
  • Did you even try searching? Commented Jul 25, 2012 at 9:55
  • Well, I actually did searched for it. Commented Jul 25, 2012 at 10:20

4 Answers 4

13

Please have a look at this RewriteCond resource.

RewriteCond %{REQUEST_FILENAME} !-f
//                                ^ this means file.
RewriteCond %{REQUEST_FILENAME} !-d
//                              ^ this means NOT, "d" means directory.
// Your rewrite rule here.
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this only works in a <Directory> block or a .htaccess file, and not in a <VirtualHost> or root config context where the REQUEST_FILENAME has not yet been completed with a full path (since it's not known). In those contexts part of the path must be added to the test manually, since REQUEST_FILENAME will just be the same as REQUEST_URI.
4

It's quite similar to shell scripting -d and -f functions.

Try something like that:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule XXX

1 Comment

That says: if requested filename is a file that exists AND is a directory that exists
2

'-d' (is directory) Treats the TestString as a pathname and tests whether or not it exists, and is a directory.

'-f' (is regular file) Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.

prefixed by an exclamation mark ('!') to negate their meaning.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

Comments

2

This should do it (replace <filename>):

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule .* <filename> [L]

It does redirection if a file, directory or link does not exist.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.