当我的链接标记在其href中具有相对路径时,这是一种奇怪的行为

I installed lampp recently in my linux machin, the sources files should be placed in /opt/lampp/htdocs directory which is annoying to work with... so what I did is creating a Symbolic link which point to that directory like that :

sudo ln -s /home/medBo/projects /opt/lampp/htdocs

Now I have my project in the following path : /home/medBo/projects/ecommerce/ and everything work fine

In a view I have a link like this :

<a href="/test/hello">click here</a>

what I expect from that link is to be pointed to localhost/projects/ecommerce/test/hello but when I hover the mouse over it or I click it, it send me to localhost/test/hello

Isn't localhost/projects/ecommerce/ considered as my site root ? what I can do about it ?

UPDATE :

Someone suggested in the comment to add <base herf="http://localhost/projects/ecommerce"> in the head of the page, well the issue with this is when I go to this url

localhost/projects/ecommerce/some-controller/some-action

and inside that page there is a link to /go-to-other-controller/other-action

The destination becomes localhost/projects/ecommerce/some-controller/some-action/go-to-other-controller/other-action

The site root is always your domain name (example.com or in this case localhost) or the IP address.

It isn't clear if the end of your path is generated through .htaccess.

If it is, you can get the file of the script which is currently executed with $_SERVER["SCRIPT_NAME"]. With PHP you can now generate the path:

$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && !in_array(strtolower($_SERVER['HTTPS']), array('off','no'))) ? 'https' : 'http';
$url .= '://'.$_SERVER["HTTP_HOST"];
$url .= (substr($_SERVER["SCRIPT_NAME"], 0, -strlen(basename($_SERVER["SCRIPT_NAME"]))));

This generates the path to the script which is executed, but without the filename of the file. Now you can add the path to it (e.g. echo $url . '/path/to/url';)

In case the path is not virtually set by .htaccess but are real directories, you may want to use $_SERVER["REQUEST_URI"] and follow the path for x amount of directories to reach the path you need, then append the new path.

Another possibility is to use a constant which is either set dynamically by one of the options above or manually by typing in the path you need.

In this case the two options underneath should work:

define("ROOT_PATH", "/projects/ecommerce/");

or

define("ROOT_PATH", "http://localhost/projects/ecommerce/");

Using the magic constants from PHP could solve your problem as well:

define('ROOT_PATH', dirname(__DIR__));

or for PHP prior to 5.3.0:

define('ROOT_PATH', dirname(dirname(__FILE__)));

To output the defined constant you can just use echo ROOT_PATH . '/path/to/url';.