Last Updated on July 31, 2021 by Amit

Fix images , css , js on RewriteRule
One of the most common issue every mod-rewrite users encounter while using RewriteRule directive to shorten their URLs is the IMG, CSS , JS and other relative resources failing to load.
If you are using RewriteRules to rewrite your URLs then you may sometimes face this kind of issue . This is a normal behavior. There is nothing wrong with your htaccess configuration and there is nothing that can be done to fix this by editing or by adding something to your htaccess file.
The solution to fix this issue is really simple and it doesn’t require a huge lines of code. Just a one single html tag can fix your problem.
In this post , I will give tell you how to fix your CSS, JS, and other relative resources for rewritten URL, but before we jump to the solution let’s first understand the reason why our files failed to load on a rewritten path.

Why IMG, CSS, JS failed to load on a rewritten path

Webpage without css htaccess

Your files failed to load because you are linking them on a web page using a relative path like in the following image example :
<img src=”something.jpg”>
Your image file should work if you use an absolute path starting with the dir name as “/” for root :
<img src=”/something.jpg”>
Now see the following rule :

RewriteRule ^foo/$ /demo.php [L]

The rule above will internally map a request for /foo to /demo.php
If you visit the file path /demo.php you will not face any issues with your relative resources but if you visit the new rewritten path /demo/ then your relative resources will fail to load. This is because the web server thinks /demo/ is a base directory and tries to append it to all relative resources changing your image path from
<img src=”something.jpg”>
<img src=”demo/something.jpg”>
As you can see the “demo” path has been appended to the image . Since /demo/something.jpg doesn’t exist thus the image 404s and fails to load.

How to solve IMG CSS JS not loading on rewritten path

It’s very simple to fix this problem. You either need to use a base tag or change the relative path to absolute in your files.
For example , if you are linking a js file using a relative path in your document, change its path from :
<script src=”something.js”>
To <script src=”/something.js”>
and do the same for images or other relative resources. While this can be tough to manually change files path one by one if you have hundreds or relative links in a document, in that case what you can do to quick fix it is just add a single liner base tag to the head section of your document.
<base href=”/”> inbetween <head> and </head> will fix all relative links in your document.

How useful was this post?

Click on a star to rate it!

Average rating 4.6 / 5. Vote count: 72

No votes so far! Be the first to rate this post.