Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mod_rewrite not loading css and js files

I have a weird problem with a mod_rewrite condition / rule.

This is the condition and rule I'm using.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.*)$ index.php?params=$1 [QSA,L]

My problem is if I visit www.example.com and www.example.com/page it loads fine but when I try to load www.example.com/page/category it loads the page but cannot find the css and javascript. It tries to load them from page/css instead of the / directory.

Any thoughts on what I've done wrong? I had a search on here and tried a few things like add

RewriteCond $1 !\.(js|ico|gif|jpg|png|css|html|swf|mp3|wav|txt)$ 

and

RewriteRule ^(images|css|javascript)(.*)$ index.php?params=$1 [QSA,L]

But that didn't seem to make much difference.

Thanks for reading

like image 513
hooligan Avatar asked Oct 22 '22 15:10

hooligan


1 Answers

The problem is that a silent rewrite will not tell the visitor's web browser that they are in fact looking at a page from a different directory path.

So a request for /page leaves the browser (correctly) thinking that it is looking at a resource which is in the top-level public directory on the web server, as are the images and CSS files.

But a request for /page/category leaves the browser (wrongly) thinking that it is looking at a resource which is in a sub-directory called page. So when the browser sends requests for the CSS and image files, it will ask the server to look for them in the /page/ sub-directory, which does not really exist. So the server returns 404 codes when the browser tries to fetch image and CSS files.

One way to get around this is to change the paths to CSS, image and other page-referenced resources to absolute paths. Start them with a forward-slash so that they are anchored relative to the actual top-level public directory. This is probably the best way to proceed if you only have a small number of resource paths to update. For example, change:

src="image-name.png"

into

src="/image-name.png"

This will force the browser to request the file using an absolute path rather than deduce the wrong location based on a relative path.

To remove the need for a RewriteCond, you can change your RewriteRule to the following:

RewriteRule ^([a-z]+(?:/[a-z]+)*)$ index.php?params=$1 [QSA,L]

This will not match anything which contains a period (dot) symbol, so requests for image and CSS files will be skipped.

like image 129
Bobulous Avatar answered Nov 02 '22 14:11

Bobulous