繁体   English   中英

Nginx Static 内容缓存 proxy_cache_bypass proxy_no_cache

[英]Nginx Static content caching proxy_cache_bypass proxy_no_cache

我在使用 nginx 作为负载平衡器时遇到问题。 I could configure it to work as a load balancer but I don't how to make it cache static contents from the proxied servers in the backend such as html,css,js, etc... This means I want nginx to weather to cache或者不基于后端服务器的响应内容,如果它更改为绕过缓存并将请求发送到后端,如果不从缓存中提供服务。 我在互联网上尝试并搜索了很多,以使用许多指令(例如 proxy_cache_bypass 和 proxy_no_cache)来实现它,但我做不到。 如果有人在此类主题方面有经验,是否有任何方法可以做到这一点。 这些是配置:

upstream backend {
    server www.webserver1.com:443 max_fails=3 fail_timeout=15s;
    server www.webserver2.com:443 max_fails=3 fail_timeout=15s;
}

server {
    listen      443 ssl;

    rewrite_log on;
    error_log   /var/log/nginx/lb.error.log;
    proxy_set_header Host      $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Proxy-Cache $upstream_cache_status;
    ssl_certificate         /etc/nginx/client.crt;
    ssl_certificate_key     /etc/nginx/client.key;
    ssl on;

    location / {
        proxy_cache backcache;
        #proxy_cache_methods GET HEAD POST;
        #proxy_cache_bypass $cookie_nocache $arg_nocache;
        #proxy_no_cache $cookie_nocache $arg_nocache;
        proxy_cache_min_uses 1;
        #proxy_cache_revalidate on;
        #proxy_cache_valid 200 4m;
        proxy_cache_lock on;
        proxy_cache_background_update on;
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_pass https://backend;
    }

}

server {
    listen 80 ;
    if ($http_x_forwarded_proto != 'https') {
        rewrite ^(.*) https://$host$1 redirect;
    }
}

这些是配置的内容。 /etc/nginx/conf.d/ 下的文件,该文件包含在主配置中。 文件是 /etc/nginx/nginx.conf 并且这两行也在主配置中。 文件:

    proxy_cache_path /var/lib/nginx/cache keys_zone=backcache:20m max_size=100m;
    proxy_cache_key "$scheme$request_method$host$request_uri$is_args$args$cookie_user";

如果这些服务器配置不正确,您的后端服务器可能是该问题的根本原因。 例如,在对 static 文件的请求中发送 Cache-Control 标头。

默认情况下,根据该文档, NGINX 尊重来自原始服务器的 Cache-Control 标头。 它不会缓存将 Cache-Control 设置为 Private、No-Cache 或 No-Store 或在响应 header 中设置 Cookie 的响应。

您可以通过添加这些指令永久更改此行为:

proxy_ignore_headers Cache-Control;
proxy_cache_valid any 30m; 

所以配置看起来像:

    location / {
        proxy_cache backcache;
        proxy_cache_revalidate on;
        proxy_cache_min_uses 3;
        proxy_cache_valid 200 302 10m;;
        proxy_cache_lock on;
        proxy_cache_background_update on;
        proxy_ignore_headers Cache-Control;
        proxy_cache_valid any 30m;
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_pass https://backend;
    }

希望它能帮助你弄清楚。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM