I'm developing a PHP website that uses url routing. I'd like the site to be directory independent, so that it could be moved from http://site.example.com/ to http://example.com/site/ without having to change every path in the HTML. The problem comes up when I'm linking to files which are not subject to routing, like css files, images and so on.
For example, let's assume that the view for the action index
of the controller welcome
contains the image img/banner.jpg
. If the page is requested with the url http://site.example.com/welcome, the browser will request the image as http://site.example.com/img/banner.jpg, which is perfectly fine. But if the page is requested with the url http://site.example.com/welcome/index, the browser will think that welcome
is a directory and will try to fetch the image as http://site.example.com/welcome/img/banner.jpg, which is obviously wrong.
I've already considered some options, but they all seem imperfect to me:
Use url rewriting to redirect requests from (*.css|*.js|...) or (css/*|js/*|...) to the right path.
Problems: Every extension would have to be named in the rewrite rules. If someone would add a new filetype (e.g. an mp3 file), it wouldn't be rewritten.
Prepend the base path to each relative path with a php function. For example:
<img src="<?php echo url::base(); ?>img/banner.jpg" />
Problems: Looks messy; css- and js-files containing paths would have to be processed by PHP.
So, how do you keep a website directory independent? Is there a better/cleaner way than the ones I came up with?