Search code examples
htmlimagerelative-pathsrc

Relative HTML Image Reference (LAMP)


Really new to web development, but I can't work out why my relative image reference isn't working. I have my index.php in DocumentRoot [/var/www/vhosts/project0/html/], with a separate folder where I have put my images [/var/www/vhosts/project0/images/]. I have looked at the permissions, and they seem to be ok; see ls -l output at [/var/www/vhosts/project0/] below:

  • drwxr-xr-x 2 aiden aiden 4096 Mar 12 18:48 html
  • drwxr-xr-x 2 aiden aiden 4096 Feb 14 12:12 images

My HTML is as follows:

<!DOCTYPE html>

<html>
  <head>
    <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
    <title>My Lecture Reader</title>
  </head>
  <body>
    <h1>CSCI S-75</h1>
    <ul>
      <img src="P001.jpg"/> <br> <!-- Works -->
      <img src="../images/P001.jpg"/> <br> <!-- Doesn't Work -->
    </ul>
  </body>
</html>

Note: I have copied P001.jpg from images/ to html/ for debugging.

I am running Xbuntu on a VirtualBox, with Apache2 as web server.

If you can help, or point me in the right direction, that would be wonderful.

Cheers,

Aiden

EXTRA DETAIL:

project0.conf extract:

<VirtualHost *:80>
    ServerName project0

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/vhosts/project0/html/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Solution

  • my relative image reference isn't working.

    You have the image folder outside the document root - so this is not going to work. With it being outside the document root, your relative client-side URL is never going to resolve (you are effectively trying to go "above" http://example.com/). Everything that you serve directly in the client-side HTML must be within the document root. (If you could directly access files above the DocumentRoot from the client-side browser then you would have a huge security vulnerability!)

    However, your server-side relative file-system path (not a URL) resolves OK, so you can access your XML files. Note that on most shared server environments your server-side script often has access to 1 directory above the "document root". This is a good place to "hide" your server-side files, since they are not directly accessible from the browser (client-side).

    Your "images" directory (which you want to access directly from your HTML) should go within the DocumentRoot eg. /var/www/vhosts/project0/html/images. Then you can access your images using a root-relative path (starting with a slash) from your index.php document in the document root, thus:

    <img src="/images/P001.jpg">