Nginx Browser Caching with Alias

2019-03-05 02:47发布

I'm attempting to set up browser caching on nginx with Django. The current (working) configuration of my nginx configuration file for static files is the following:

server {

    listen   443 ssl;
    server_name SERVER;

    ssl_certificate     /etc/ssl/CERT.pem;
    ssl_certificate_key /etc/ssl/KEY.key;
    ssl_protocols       SSLv3 TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    client_max_body_size 4G;

    access_log /webapps/site/logs/nginx-access.log;
    error_log /webapps/site/logs/nginx-error.log;

    location /static/ {
        alias   /webapps/site/static/;
    }

    # other locations, etc.
}

I would like to set up a rule that caches images etc. within the browser to limit the number of requests per page (there are often 100 or so images per page but the images are the same throughout the entire site). I tried adding a few variations of the following rule:

location ~* \.(css|js|gif|jpe?g|png)$ {
  expires 365d;
  add_header Pragma public;
  add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

However, when I do this, I get nothing but 404 errors (though the configuration file checks out and reloads without errors). I believe that this has something to do with the alias but I am not sure how to fix it.

Any suggestions would be appreciated!

1条回答
The star\"
2楼-- · 2019-03-05 03:22

You are missing the rootdirective for the images location block. Therefore, nginx will look for the files in the default location which varies by installation and since you have most likely not placed the files there, you will get a 404 Not Found error.

It works for the /static/location block because you defined an alias. I suspect though that the alias is simply what should be the root for both. If so, then try ...

server {

    listen   443 ssl;
    server_name SERVER;
    root /path/to/web/root/folder/;

    [...]

    # Your locations ... Most likely no need for alias in any.
}
查看更多
登录 后发表回答