![为特定 URL 启用 nginx 浏览器缓存](https://linux22.com/image/628491/%E4%B8%BA%E7%89%B9%E5%AE%9A%20URL%20%E5%90%AF%E7%94%A8%20nginx%20%E6%B5%8F%E8%A7%88%E5%99%A8%E7%BC%93%E5%AD%98.png)
如何为特定 URL 启用 nginx 缓存?我有一个 django web 应用程序,我将 CSS、JavaScript 等静态文件放在一个名为 static 的文件夹中,我可以通过以下方式访问它们http://example.com/static/我想要配置 nginx 以便仅从此 URL 捕获这些文件。我读过http://www.nginxtips.com/how-to-enable-browser-cache-static-files-on-nginx/但那里没有解释此选项。我尝试了以下配置并重新启动了我的 nginx 服务器,但出现了错误。这是我的 sites-available/default
配置文件。问题是什么?
server {
listen 80;
listen 443 ssl;
server_name www.example.com example.com;
ssl_certificate /var/www/example/ssl/ssl.crt;
ssl_certificate_key /var/www/example/ssl/ssl.key;
location /static (jpg|jpeg|png|gif|ico|css|js)$ {
alias /var/www/example/static;
expires 3d;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}
location /media {
alias /var/www/example/media;
}
location / {
proxy_pass http://127.0.0.1:8000;
}
}
这是 nginx 日志文件内容……
2014/03/07 13:02:28 [error] 25189#0: *22 open() "/etc/nginx/html/static/css/wait.css" failed (2: No such file or directory), client: 2.178.27.157, server: www.example.com, request: "GET /static/css/wait.css HTTP/1.1", host: "example.com", referrer: "http://example.com/"
2014/03/07 13:02:28 [error] 25189#0: *23 open() "/etc/nginx/html/static/img/infographi.png" failed (2: No such file or directory), client: 2.178.27.157, server: www.example.com, request: "GET /static/img/infographi.png HTTP/1.1", host: "example.com", referrer: "http://example.com/"
2014/03/07 13:02:29 [error] 25189#0: *23 open() "/etc/nginx/html/favicon.ico" failed (2: No such file or directory), client: 2.178.27.157, server: www.example.com, request: "GET /favicon.ico HTTP/1.1", host: "example.com"
2014/03/07 13:08:41 [emerg] 25220#0: invalid location modifier "/static" in /etc/nginx/sites-enabled/default:8
2014/03/07 13:08:41 [emerg] 25221#0: invalid location modifier "/static" in /etc/nginx/sites-enabled/default:8
2014/03/07 13:09:50 [emerg] 25255#0: invalid location modifier "/static" in /etc/nginx/sites-enabled/default:8
2014/03/07 13:09:50 [emerg] 25256#0: invalid location modifier "/static" in /etc/nginx/sites-enabled/default:8
答案1
来自nginx 维基百科似乎“/static”和正则表达式模式之间有一个空格。Location 只接受一个“uri”参数,而不是两个……并且 nginx 会将该空格解释为参数分隔符。
您还需要告诉位置块您想要使用“~”或“~*”修饰符匹配正则表达式。
你可以尝试一下
location ~* "/static.*(jpg|jpeg|png|gif|ico|css|js)$" {
而不是你已经拥有的,看看它是否能满足你的要求。
答案2
此文件夹中还有其他文件吗?如果没有,或者如果可以公开这些文件,您可以简化配置:
server {
listen 80;
listen 443 ssl;
server_name www.example.com example.com;
ssl_certificate /var/www/example/ssl/ssl.crt;
ssl_certificate_key /var/www/example/ssl/ssl.key;
root /var/www/example;
location / {
proxy_pass http://127.0.0.1:8000;
}
location /media/ {
# it's ok to have empty location
}
location /static/ {
expires 3d;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}
}