Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a website with url routing directory independent

Tags:

People also ask

What is URL routing?

URL routing allows you to configure an application to accept request URLs that do not map to physical files. A request URL is simply the URL a user enters into their browser to find a page on your web site.

What is Route programming?

A route is a section of Express code that associates an HTTP verb ( GET , POST , PUT , DELETE , etc.), a URL path/pattern, and a function that is called to handle that pattern. There are several ways to create routes.

What is Javascript routing?

A Javascript router is a key component in most frontend frameworks. It is the piece of software in charge to organize the states of the application, switching between different views.


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?