简体   繁体   中英

How to use “relative” URLs?

i have a doubt, in an HTML file I have the following structure:

    MAIN -> index.php
         -> IMAGES -> image.jpg

In an 'img' tag should I use this:

    <img src="IMAGES/image.jpg">

Or this?

    <img src="/IMAGES/image.jpg">

Note that in the second example I added the slash before IMAGES. This is my question.

两者都适用于这种情况,但我建议使用您的第一个选项(相对路径),因此如果将来您将整个项目移动到新的根目录下,您的所有站点都将继续工作。

Both would work but if you don't expect to ever move your IMAGES directory, go with /IMAGES/image.jpg . This would be preferable because you'll be able to use that same uri anywhere in your markup (say, if you add MAIN/SCRIPTS/newscript.php , then /IMAGES.. will work, IMAGES/image.jpg would not). If, however, you always intend to store IMAGES as a directory at the same level as index.php, but you might end up moving index.php somewhere else, then you might consider using IMAGES/image.jpg .

In this case, they're exactly the same, but consider this updated example:

    MAIN -> index.php
         -> ABOUT -> index.php
         -> IMAGES -> image.jpg

Now, inside ABOUT/index.php there is a difference, because

<img src="IMAGES/image.jpg"> # => /ABOUT/IMAGES/image.jpg

<img src="/IMAGES/image.jpg"> # => /IMAGES/image.jpg

The "safety" of using relative URLs depends on if you will be using subdirectories in your URLs.

Assuming your file structure,

If you are at http://example.com/index.php , then the url IMAGES/image01.jpg will work.

If you are at http://example.com/somedir/index.php , then "IMAGES/image01.jpg will not load (It will be looking for http://example.com/somedir/IMAGES/image01.jpg instead of your intended http://example.com/IMAGES/image01.jpg )

This means that using relative URLs is "dangerous" if you:

1) Move or copy your index.php file into a subdirectory 2) Use url rewriting to remove index.php from your URLs (and so hae URLs like example.com/some/location rewrite to example.com/index.php?l=some/location )

Your safest bet is to use a variable to get your base URL:

define('BASE_URL', 'http://example.com');

Then later in your HTML:

<img src="<?php echo BASE_URL; ?>/IMAGES/image01.jpg" alt="" />

If you move your site in the future, you can change the BASE_URL constant.

Both should work, but I'd suggest using the slash. When you add the slash before hand, it means to look in the top most directory. With out it it means relative to the current file.

If you use the method with the slash before hand it allows you to move the file, or copy html to other files and it won't matter where they are.

On a side note, without the slash is called a relative path, and with the slash is called and absolute path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM