nginx image folder and declaration

May 19, 2017 215 views
Nginx Ubuntu 16.04

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.

1 Answer

@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.

Have another answer? Share your knowledge.