Apache RewriteRule to treat images, css and js files as normal

.htaccessapache-2.2mod-rewriterewrite

i need to set up an apache RewriteRule in order to have this behavior:

example.com/foo => index.php?module=foo&action=&args=
example.com/foo/bar => index.php?module=foo&action=bar&args=
example.com/foo/bar/baz => index.php?module=foo&action=bar&args=baz
example.com/foo/bar/baz/foobaz => index.php?module=foo&action=bar&args=baz/foobaz

I wroted this regex:

RewriteRule ^(.[^/]*)(\/)?(.[^/]+)?(\/)?(.+)?$ index.php?module=$1&action=$3&args=$5 [L,QSA]

It works well, i only need to tell apache to ignore all urls that end with some specific estension (for example, .jpg, .png, .css, .js, .gif, etc..); Those should be treated as normal, e.g. example.com/css/style.css should show the CSS file (is it exists).

Any idea?

Best Answer

An easy way to get around it is this

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.[^/]*)(\/)?(.[^/]+)?(\/)?(.+)?$ index.php?module=$1&action=$3&args=$5 [L,QSA]

That tells apache to not run the rule if the file is a real file on the system that can be served up.. Now you if you want to do it for just image/css/js files you could probably do

RewriteCond %{REQUEST_FILENAME} !^(.*).(js|jpg|css|gif)$
RewriteRule ^(.[^/]*)(\/)?(.[^/]+)?(\/)?(.+)?$ index.php?module=$1&action=$3&args=$5 [L,QSA]

That one is untested but you get the idea.