views:

122

answers:

2

If user visits /abc,

and there is no file/directory named abc under /,redirect it to /test.php?from=abc,

but if it exists,don't redirect.

A: 
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ test.php?from=$1

RewriteCond is a conditional - the following rule will only execute if the condition is true.

The -f test checks if a file exists, the -d test checks if a directory exists.

SCRIPT_FILENAME will be set to the system path that Apache would use to fetch a file (e.g. /var/www/html/blah.html)

So it checks to see that the file doesn't exist, then it checks to see that the directory doesn't exist. If both those conditions are met, it processes the rule.

Example:

  • Your DOCUMENT_ROOT is set to /var/www/html
  • Your user requests http://yoursite/blah.html
  • Firstly we check to see if /var/www/html/blah.html is a file
  • Then we check to see if /var/www/html/blah.html is a directory
  • If there is no file or directory of that name, it rewrites to http://yoursite/test.php?from=blah.html

Documentation for RewriteCond

mopoke
Does it only affect the `RewriteRule` right behind or all `RewriteRule`s?
It affects only the following rule.
mopoke
A: 

May be like this, tested on xampp in windows.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ /test.php?from=$1
S.Mark