Nginx静态内容缓存proxy_cache_bypass proxy_no_cache

问题描述 投票:0回答:1

我在使用nginx作为负载均衡器时遇到问题。我可以将其配置为充当负载平衡器,但是我不打算如何使其从后端的代理服务器(例如html,css,js等)中缓存静态内容。这意味着我希望nginx能够如果它更改为绕过缓存并向后端发送请求,或者不从缓存提供服务,则根据后端服务器响应的内容来决定是否缓存。我尝试并在Internet上进行了大量尝试,以使用诸如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";
nginx caching
1个回答
0
投票

如果您的后端服务器配置不正确,则可能是该问题的根本原因。例如,将对请求的Cache-Control标头发送到静态文件。

默认情况下,根据docs,NGINX遵守源服务器的Cache-Control标头。它不缓存将Cache-Control设置为Private,No-Cache或No-Store或在响应标头中设置Set-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;
    }

希望它将帮助您找出答案。

© www.soinside.com 2019 - 2024. All rights reserved.