无法让 nginx 缓存通过 https 反向代理工作

无法让 nginx 缓存通过 https 反向代理工作

正如标题所示,我无法让 nginx 缓存在我的反向代理上运行。这是我的 nginx 的服务器块配置:

proxy_cache_path /opt/cache/nginx/cache2.xxx.net levels=1:2 keys_zone=test_zone:10m;

server {
    server_name cache2.xxx.net;
    listen 443 ssl http2; #listen for https connections, http2 enabled
    listen 80; # listen for http connections too

    # certificate's stuff
    ssl_certificate /etc/letsencrypt/live/xxx.net/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/xxx.net/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;

    # main test location
    location  / {
        # Passed headers
        proxy_set_header  X-Forwarded-For $remote_addr;
        proxy_set_header  X-Forwarded-Proto $scheme;
        proxy_set_header  User-Agent $http_user_agent;
        proxy_set_header  Host $host;
        proxy_set_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With,X-Ajax-Referer';

        # Timeouts
        proxy_connect_timeout       20;
        proxy_send_timeout          20;
        proxy_read_timeout          20;
        send_timeout                20;                 

        # Caching directives
        proxy_cache test_zone;
        proxy_cache_background_update off;
        proxy_cache_convert_head on;
        proxy_cache_key "$host$request_uri$request_method";
        proxy_cache_lock off;
        proxy_cache_lock_age 5s;
        proxy_cache_lock_timeout 5s;
        proxy_cache_methods GET HEAD;
        proxy_cache_min_uses 1;
        proxy_cache_use_stale off;
        proxy_cache_valid 200 302 10m;


        if ($scheme = https) {
            add_header "Content-Security-Policy" "upgrade-insecure-requests";
        }

        proxy_pass http://XXX.XXX.XXX.XXX; # remote server, over http
        add_header Caching $upstream_cache_status; # Add an header to show the caching status
   }
}

这个配置似乎没问题。然后我做了一些测试:HTTP 流量的缓存似乎没问题:

curl -D - -o /dev/null -k -s http://cache2.xxx.net/login

给了我这个结果:

HTTP/1.1 200 OK
Server: xxx-nginx
Date: Fri, 03 Aug 2018 21:54:16 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Caching: HIT

然后我又做了一次测试,但这次是通过 HTTPS(http2 版本,但没有任何区别,我也尝试过不用它),结果如下:

curl -D - -o /dev/null -k -s https://cache2.xxx.net/login

HTTP/2 200
server: nginx
date: Fri, 03 Aug 2018 21:55:42 GMT
content-type: text/html; charset=UTF-8
content-security-policy: upgrade-insecure-requests

这次 Cacheing 标头完全缺失,这是因为 $upstream_cache_status 变量具有空值。但为什么呢?

我注意到的另一件奇怪的事情是 HTTP 请求具有与 HTTPS 请求不同的“服务器”标头。

相关内容