Nikola Obreshkov
Nikola Obreshkov

Reputation: 1748

Apache .htaccess to redirect all URLs except for files and directories

I am developing a web site currently located at a subdomain. In the .htaccess file I have the following:

RewriteEngine on
RewriteBase /

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

RewriteRule ^([a-zA-Z_\-]+)/?$ /index.php?url=$1 [L,NC]
RewriteRule ^([a-zA-Z_\-]+)/(.+)/?$ /index.php?url=$1&$2 [L,NC]

When I try to load an existing css file e.g. http://subdomain/path/to/existing/file.css Apache still redirects it to index.php. Is it possible to redirect all URLs to index.php except for existing files and directories?

Upvotes: 0

Views: 432

Answers (1)

Mike Rockétt
Mike Rockétt

Reputation: 9007

The problem with your code is that the last rule is not conditioned, as you can only have one RewriteRule per condition or set thereof.

There's more than likely a better way to do this (perhaps using the skip flag S), but you can repeat your conditions in the meantime.

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

RewriteRule ^([a-z_-]+)/?$ index.php?url=$1 [L,NC]

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

RewriteRule ^([a-z_-]+)/(.+)/?$ index.php?url=$1&$2 [L,NC]

Also, and as you have specified the NC flag, you need not specify A-Z in the pattern. Also, no need to escape the hyphen -.

Update: You could also try setting an environment variable, per this answer:

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

# If the conditions above are true, then set a variable to say so
# and continue. 
RewriteRule ^ - [E=TRUE:YES]

RewriteCond %{ENV:TRUE} = YES
RewriteRule ^([a-zA-Z_\-]+)/?$ /index.php?url=$1 [L,NC]

RewriteCond %{ENV:TRUE} = YES
RewriteRule ^([a-zA-Z_\-]+)/(.+)/?$ /index.php?url=$1&$2 [L,NC]

Upvotes: 3

Related Questions