ProtectedVoid
ProtectedVoid

Reputation: 1315

htaccess Rewrite rule exclude files with extensions

I've got the following Rewrite rule in my htaccess file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+) index.php [L]

This way I'm preventing Apache to manage 404 errors and redirect to a specific file when the error occurs. When I type a non-existing URI, Apache just redirects to "index.php" as expected. Everything as expected so far. The problem comes when that rule affects files with extensions. First example is "favicon.ico" automatically requested by the browser, calls my "index.php" script too and this means two calls to the same script which is an undesired behaviour. This occurs when I request a non-existing file in HTML tags as well (all are considered the same: HTTP requests in the end).

Is there a way I can exclude files with extensions from the rule?

Example of desired behaviour:

I want these to be handled by the rule and redirected to index.php (rule already does it)

http://example.com/thisdoesntexist
http://example.com/thisdoesnt/exist

I want these to be handled by Apache's 404 error and not by the rule

http://example.com/favicon.ico
http://example.com/folder/myimage.png

Thanks in advance.

Upvotes: 1

Views: 1014

Answers (1)

Amit Verma
Amit Verma

Reputation: 41219

If http: //example.com/favicon.ico and http: //example.com/folder/myimage.png are nonexistent files and you want them to be handed by your Error document instead of the rule ,you can exclude them from the rule.

The easiest way to do this is to exclude . dot char in regex pattern. You can use ^([^.]+)$ to match any uri character(s) except the dot.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+)$ index.php [L]

Upvotes: 2

Related Questions