For my NGINX server I have a virtual server set up just to dish out static content. At the moment I'm trying to set it up so that images have an expiry date. However, when I create a location directive for this, everything just results in a 404.

My configuration right now is looking like this:

/srv/www/static.conf

server {
    listen                          80;
    server_name                     static.*.*;

    location / {
            root                    /srv/www/static;
            deny                    all;
    }

    location /images {
            expires                 1y;
            log_not_found           off;
            root                    /srv/www/static/images;
    }
}

Note, this file is included from /etc/nginx/nginx.conf, inside a http directive

I'm trying to access the image, at, let's say... static.example.com/images/screenshots/something.png. Sure enough, the image also exists at /srv/www/static/images/screenshots/something.png. However, going to said address does not work and simply tells me 404 Not Found.

However, if I remove location /images and change location / to the following...

location / {
    root /srv/www/static;
}

It works! What am I doing wrong here?


Solution 1:

Your configuration is following nginx configuration pitfalls You should read it before configuring nginx.

To answer your question, you should not define root in location, define it once and the location tag will automatically let you assign access to specific directories.

Also instead of defining custom root for images directory, use try_files. The $uri will map /images/ directory with /static/images/.

Try this configuration:

server {
    listen                          80;
    server_name                     static.*.*;
    root                            /srv/www;

    location /static/ {
            deny                    all;
    }

    location /images/ {
            expires                 1y;
            log_not_found           off;
            autoindex               off;
            try_files $uri static/images$uri;
    }
}