12

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?

Jesse Brands
  • 223
  • 1
  • 2
  • 8

1 Answers1

17

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;
    }
}
techraf
  • 4,163
  • 8
  • 27
  • 44
phoops
  • 2,073
  • 4
  • 18
  • 23
  • Thank you! I have read the pitfalls, but I guess my memory failed me. This works, though I edited it slightly for my purposes. – Jesse Brands May 16 '14 at 21:02
  • Yeah I re-read parts of it from time to time myself, there's a reason it has a separate wiki page for it ;) – phoops May 16 '14 at 21:09
  • If defining `root` inside `location` is bad practice, how come they're doning it themselves in [docs/http/ngx_http_core_module.html#alias](http://nginx.org/en/docs/http/ngx_http_core_module.html#alias)? (see where it says "*it is better to use the root directive instead*") **CORRECTION**: okay, it seems that what's wrong is defining the primary root in a location, not just any root – mehov Aug 03 '17 at 10:42