php – .htaccess rewrite rule breaks css and javascript when non existant sub directory or trailing slash is in url-ThrowExceptions

Exception or error:

I noticed that adding a trailing / to index.php breaks css and javascript which was explained here- what-happens-when-i-put-a-slash-after-a-php-url

My rewrite rule takes whatever string is after the domain and a forward slash and puts it into the GET variable q. So foo.com/foo works fine and I can access /foo in the GET variable q. How do I get any non existent resource requested in url string to work similarly? Make foo.com/foo/ OR foo.com/foo/foo etc. redirect to index.php and not break css and javascript.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ ./index.php?q=$1 [NC,L,QSA]
</IfModule>

My rewrite rule works when a query string is appended to index.php or when /index.php is replaced with /foo but breaks js and css when additional directories are added like /foo/ or /foo/foo. How does the rule need to be written to prevent this?

How to solve:

It appears that you use relative links for including your javascript or css files.
So, all you have to do is make your file addresses absolute, like /js/search.js.
Your rewrite rule is correct and it won’t forward the actual files to your index.php file. But when you say src='js/search.js', it means index.php/js/search.js for the browser, and that is not an actual file address.

Leave a Reply

Your email address will not be published. Required fields are marked *