Tuesday, 10 September 2013

acceptable mod_rewrite friendly-url approach?

acceptable mod_rewrite friendly-url approach?

I try to rewrite all url's to a single php file, unless the url leads to
an existing file because existing files like images should be handled by
the server directly. But if someone uses a url that looks like a file, and
this file doesn't exist, it should get a 404.
I came up with the following .htaccess file. Is this a valid approach? It
will be on a production server this friday so I would like to know for
sure that there is no security risk or is a bad practice of some kind.
The first rule should make sure that any url that looks like if a file is
being requested will get 404 (only if the file doesn't exist of course).
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.([-A-z0-9]+)$ - [R=404,L]
If above doesn't match, there is a second rule that rewrites all other non
existing files to index.php (like eg /products/23). In this case index.php
will handle the rest of the routes.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [L]
If no rule mathes, it means it is an existing file and will be served by
apache directly, like existing images and scripts.
Is this a valid approach? Thanks.

No comments:

Post a Comment