Site looks messy after using RewriteRule?

Sometimes when we use RewriteRule directive to shorten our urls we get into a starnge trouble. Our site looks messy as it loads without css , Javascript , images and other relative resources.
This is the question I often see users posting on StackOverflow.
A few years ago I answered a similar question on StackOverflow and now posting this here with some examples and explanations so that it can help readers like you who are having the same issue.

Why is my site loading without css , js and images?


Before we get to the solution , lets first see what happened to the site.
If you check the source code of your website , you will see that your files are loading from unknown directries not from the directories these files should load from. Forexample if your images are located inside images folder you will notice that instead of images folder your images are trying to load from a unknown or not-found directory.

This problem is most often caused when you link your css, js and image files using a relative path (a file path that is relative to the current dir) By relative path , I mean you include your (an image example) images in your document something like the following :

<img src="images/file.jpg">


The html code above tells server to load an image file file.jpg that is located inside images dir on server. If the url to the page where this image included is example.com/file.php then your image will load correctly from the expected directory. But if you rewrite this url to example.com/home/file your webserver will append the first url path /home to all relatively linked files on your webpage. This happens due to the absence of leading slash in the file path. If you put a slash at the of your file path then your site will load normally.
Putting a slash at the end of each files may be a bit complex if you have 100s of relative files in a webpage.
In that case you can simply use a one liner base tag to fix the relative resources in your document.

Solutions


To fix the site loading without css , js and other relative resources issues you can either change your links from relative to absolute ones.
Here is an example to do that :
Change your relative css link from the following format :

<link href="css/style.css">



To

<link href="/css/style.css">



Or

A quick an one liner solution


Use an html base tag inside the <head> tag .

Use HTML base tag to fix relative resources in a document


Base tag adds the base dir in your relative file path. So instead of looking looking into the URL path your server will look the href attribute of base tag and use that href value for all relative files.
Place a base tag in the head section of your document, the following is an example of the base tag :

<base href="/">

Post a Comment

0 Comments