上游服务器正在发送带有 标头的 404 Cache-Control: no-cache
。
因此,nginx 不会缓存该请求。我该如何强制它缓存该请求?
仅当上游响应具有 404 状态代码时才需要此缓存。
它可以保留原始标题并将其传递给客户端,但我不希望它向页面发送“新鲜”请求。
我也不想完全删除标头,因为某些请求会将相应的“缓存控制”标头设置为在 24 小时内过期。因此我无法使用proxy_ignore_headers
。
答案1
我很幸运,我可以根据响应代码(404)并通过拦截错误来做到这一点:
#user www-data;
#worker_processes 4;
#pid /run/nginx.pid;
#
#events {
# worker_connections 768;
# # multi_accept on;
#}
user www-data;
worker_processes 4;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
#access_log /dev/null;
#error_log /dev/null;
sendfile off;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
proxy_cache_path /tmp/nginx levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
server {
listen 443 default_server ssl;
listen [::]:443 default_server ssl;
server_name localhost;
ssl on;
ssl_certificate /opt/bitnami/nginxssl/nginxssl.crt;
ssl_certificate_key /opt/bitnami/nginxssl/selfbuild.key;
recursive_error_pages on;
location / {
proxy_pass https://localhost:9443/;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache STATIC;
# Let the Set-Cookie header through.
add_header X-Proxy-Cache $upstream_cache_status;
proxy_cache_valid 404 60m;
error_page 404 /404.html;
proxy_intercept_errors on;
}
location /404.html {
proxy_pass https://localhost:9443/404.html;
proxy_hide_header Set-Cookie;
proxy_hide_header Cache-Control;
proxy_hide_header Expires;
proxy_hide_header Pragma;
proxy_hide_header X-Accel-Expires;
proxy_ignore_headers "Set-Cookie" "Cache-Control" "Expires" "X-Accel-Expires";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache STATIC;
add_header X-Proxy-Cache $upstream_cache_status;
proxy_cache_valid 404 60m;
}
}
}