I have a mod_rewrite to allow example.com/location as example.com/?page=location

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} !^page
RewriteRule ^(.*)/?$ /?page=$1 [L]

But how do I ignore certain files or all folders, so my example.com/styles.css and example.com/scripts.js are not changed to example.com/?page=styles.css and example.com/?page=scripts.js

Ignore all files with an ending .css, .js, .php, .html, .png, .* etc


Instead of making exceptions for a growing list of expected file types, it is more usual (and more flexible) to just make an exception if the file exists (or, optionally, is a directory). For example:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} !^page
RewriteRule ^(.*)/?$ index.php?page=$1 [L]

The above says... if the request is not a file or directory on the filesystem then proceed and rewrite the request.

Since all your CSS, JS, images, etc. are all physical files on the filesystem then they won't be rewritten.

Apache even provides a one-liner (part of mod_dir) that essentially does the same thing:

FallbackResource /index.php

This internally rewrites all requests for non-existent files to /index.php. However, you would then need to check the requested URL (eg. $_SERVER['REQUEST_URI'] in PHP), rather than the page URL param in order to route the request.


| improve this answer | |

This should work:

RewriteEngine On
RewriteCond %{REQUEST_URI} !.png$ [NC]
RewriteCond %{REQUEST_URI} !.html$ [NC]
RewriteCond %{REQUEST_URI} !.php$ [NC]
RewriteCond %{REQUEST_URI} !.css$ [NC]
RewriteCond %{REQUEST_URI} !.jpg$ [NC]
RewriteCond %{QUERY_STRING} !^page
RewriteRule ^(.*)/?$ /something.php?page=$1 [L]

It scans the URL for each extension one by one regardless of the casing one uses. For example, your script won't execute if someone requested something with a .jpg or even .JpG extension.

Also, I recommend putting in the script file name in for the rewrite rule otherwise extra processing will be done in the background by apache because it has to figure out what default index file to use to insert between /? in /?page=$1.

| improve this answer | |
  • Thank you, works perfectly and I understand a little bit more of .htaccess! – Zed Dec 14 '15 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.