NGINX 版本:nginx/1.15.12
我正在尝试将缓存控制标头添加到位置块中,该块具有指向指定位置的 try_files。不幸的是,似乎 add_header 指令被忽略了,即使 add_header 已经总是添加。
从文档中,我看到如果当前配置中没有 add_header 指令,则指令必须从前一个配置级别继承。由于最终当前位置将是 @proxy 位置,它没有 add_header 指令,我不明白为什么不从父位置添加这些。
<块引用>可能有几个 add_header 指令。当且仅当当前级别上没有定义 add_header 指令时,这些指令才从先前的配置级别继承。
少说话,多代码(在本例中为配置):
http {
error_log /dev/stdout info;
include mime.types;
default_type application/octet-stream;
sendfile on;
sendfile_max_chunk 1m;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 620s;
server_tokens off;
server {
access_log /dev/stdout main;
listen 8080 default_server;
server_name test;
# brotli
brotli off;
brotli_static on;
brotli_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/xml+rss application/json application/javascript image/svg+xml;
# gzip
gzip on;
gzip_static on;
gzip_min_length 500;
gzip_http_version 1.1;
gzip_proxied any;
gzip_comp_level 7;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/xml+rss application/json application/javascript image/svg+xml;
location @proxy {
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
rewrite ^(.*)$ /whatever/test/path/$1 break;
proxy_pass http://1.2.3.4;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
try_files $uri/index.html @proxy;
# keep the cache for 20 seconds
add_header Cache-Control "public, max-age=20";
}
location ~* \.(?:jpg|jpeg|gif|png|ico|svg|css|js)$ {
try_files $uri @proxy;
# keep the cache for a long time years
add_header Cache-Control "public, max-age=63113904, immutable";
}
}
}
目前我设法通过使用代理配置创建一个单独的文件来解决这个问题,我在包含 add_header 指令的每个位置导入该文件,但我想找到是否有其他更好的解决方案适合我的情况。如有必要,我可以提供当前的修复配置以便更好地理解。