: Mod_rewrite ignore Stylesheet and JavaScript I have a mod_rewrite to allow example.com/location as example.com/?page=location RewriteEngine On RewriteBase / RewriteCond %{QUERY_STRING} !^page RewriteRule
I have a mod_rewrite to allow example.com/location as example.com/?page=location
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} !^page
RewriteRule ^(.*)/?$ /?page= [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
More posts by @XinRu657
2 Comments
Sorted by latest first Latest Oldest Best
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= [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.
Reference: httpd.apache.org/docs/2.2/mod/mod_dir.html#fallbackresource
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= [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=.
Terms of Use Create Support ticket Your support tickets Stock Market News! © vmapp.org2024 All Rights reserved.