Question

nginx image folder and declaration

I have two server blocks and as such

/var/www/mydomain.com/html /var/www/m.mydomain.com/html

What’s the proper nesting? it should be

/var/www/mydomain.com/images /var/www/mydomain.com/js /var/www/mydomain.com/css

or?

in which case how do i get the site to recognize images in those folders since they only seem able to look at the html folder.


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

@ariziragoran

What you set as root in your server block is where NGINX will look for each request.

If your root is setup as:

root /var/www/html;

and a request on domain.com comes through for images/my_photo.png, then NGINX will look to /var/www/html/images for my_photo.png.

You can setup different root directories for locations if you want to keep your assets below the web root. For example, if you have this as your root:

root /var/www/mydomain.com/html;

You could add location blocks, like so, to access the assets below ./html.

location /css {
    alias /var/www/mydomain.com/css;
}

location /images {
    alias /var/www/mydomain.com/images;
}

location /js {
    alias /var/www/mydomain.com/js;
}

I’m using alias instead of root so I can specify the full path. You could just as well use something such as:

location /css {
    root /var/www/mydomain.com;
}

location /images {
    root /var/www/mydomain.com;
}

location /js {
    root /var/www/mydomain.com;
}

In the above, you’ll notice that all the root directives are the same and that’s due to how NGINX handles the request. It appends the request on to the root, so if we added the directories to the end of each root (as we did with alias), the result would be a 404.

As an example, let’s say we use this for /js instead of the above:

location /js {
    root /var/www/mydomain.com/js;
}

When a request comes through for /js, NGINX will look to:

/var/www/mydomain.com/js/js

Which will result in a 404 because /js/js doesn’t exist.