Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rewriterule in htaccess to match certain file extensions

How can I look for an instance for certain file extensions, like .(jpg|png|css|js|php), and if there is NOT a match send it to index.php?route=$1.

I would like to be able to allow period's for custom usernames.

So, rewrite http://example.com/my.name to index.php?route=my.name

Current setup:

.htaccess:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+)$ index.php?route=$1 [QSA,L]
</IfModule>

What works:
http://example.com/userpage -> index.php?route=userpage
http://example.com/userpage/photos -> index.php?route=userpage/photos
http://example.com/file.js -> http://example.com/file.js
http://example.com/css/file.css -> http://example.com/css/file.css

What I need to work in addition to above:
http://example.com/my.name -> index.php?route=my.name

like image 483
wdavis Avatar asked Oct 27 '10 22:10

wdavis


People also ask

What is RewriteRule in htaccess?

htaccess rewrite rules can be used to direct requests for one subdirectory to a different location, such as an alternative subdirectory or even the domain root. In this example, requests to http://mydomain.com/folder1/ will be automatically redirected to http://mydomain.com/folder2/.

How RewriteRule works?

RewriteRule specifies the directive. pattern is a regular expression that matches the desired string from the URL, which is what the viewer types in the browser. substitution is the path to the actual URL, i.e. the path of the file Apache servers. flags are optional parameters that can modify how the rule works.

What is mod_ rewrite in apache?

The Apache module mod_rewrite is a very powerful and sophisticated module which provides a way to do URL manipulations. With it, you can do nearly all types of URL rewriting that you may need. It is, however, somewhat complex, and may be intimidating to the beginner.


2 Answers

Add an extra RewriteCond to exclude the conditions that you don't want rewritten. Use a ! before the regular expression to indicate that any files matching should fail the condition. The RewriteCond below is untested, but should give you an idea of what you need:

RewriteCond %{REQUEST_URI} !\.(jpg|png|css|js|php)$
like image 150
Dingo Avatar answered Nov 15 '22 23:11

Dingo


Have you tried reversing the logic? Something like

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule \.(jpg|png|css|js)$ - [L]

This will not do a rewrite for any file with a .jpg, .png, .css, or .js extension. Then add your existing rules so that non-file, non-directory requests get rerouted to index.php.

like image 45
Harper Shelby Avatar answered Nov 16 '22 01:11

Harper Shelby