Relative URL is relative to wrong absolute URL on web

Bob Johnson asked:


I am building a website. The files are:


As we know, people can visit my site’s dir/index.php page using different URLs:


I have a link in /dir/index.php

<a target="_blank" href="pic.jpg">

which I want to relativly link to /dir/pic.jpg

The Problem

        |     |                                 |
        |     | 1                               |
        |     |                                 |
        |     |       2 or 3                    |
        | index.php ---------> pic.jpg          |

The href="pic.jpg" leads people to different places when people visit the web via different urls.

People using url 1 get /pic.jpg , and others using url 2 or 3 get /dir/pic.jpg

The same problem goes with not just <a> but other HTML tags.

How can I write a relative URL in /dir/index.php that links to /dir/pic.jpg whatever URL visitors use?

I need to keep folder dir portable (I may change dir‘s name, or use dir folder on another website, so it may have different path). We need a solution other than hardcoding href="/dir/pic.jpg".

My answer:

The problem is that you have somehow not added a trailing slash to the first URL. If this directory actually exists on your server, then you would have had to intentionally misconfigure the web server to do this. You should undo that configuration, so that the server redirects the first example to the second example (the default).

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.