Yehonatan
Yehonatan

Reputation: 3225

RewriteRule only if directory or file does not exists

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.

Upvotes: 4

Views: 11282

Answers (4)

Adi
Adi

Reputation: 5169

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.

Upvotes: 13

Bruno Schäpper
Bruno Schäpper

Reputation: 1302

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.

Upvotes: 2

xdazz
xdazz

Reputation: 160833

'-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

Upvotes: 2

Geoffrey Brier
Geoffrey Brier

Reputation: 799

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

Upvotes: 4

Related Questions