Nginx $upsteam_cache_status 自定义标头不会出现

Nginx $upsteam_cache_status 自定义标头不会出现

我正在尝试调试 nginx 代理缓存,为此我需要查看该$upstream_cache_status值。我的配置如下:

http {
    ...
    proxy_cache_path /tmp/cache_nginx levels=1:2 keys_zone=cfcache:10m max_size=2g inactive=10m use_temp_path=off;
    ...

    server {
        listen 80;
        listen [::]:80;
        server_name domain.com;
        root  /home/site/wwwroot;
        error_log /home/logfiles/nginx/error.log;

        proxy cache cfcache;

        add_header Custom-header-test Value;
        add_header X-Cache-Status $upstream_cache_status always;


        #index file redirect
        index index.php;

        location = /favicon.ico {
          log_not_found off;
          access_log off;
        }

        location = /robots.txt {
          allow all;
          log_not_found off;
          access_log off;
        }

        # Block access to "hidden" files and directories whose names begin with a
        # period. This includes directories used by version control systems such
        # as Subversion or Git to store control files.
        location ~ (^|/)\. {
           return 403;
        }

        location / {
            try_files $uri $uri/ $uri.html @php;
        }

        location @php {         
            rewrite ^(/[^/]+)$ $1.php last;
            rewrite ^(/[^/]+)/(.*)$ $1.php?q=$2 last;
        }

        #404 error page
        error_page 404 /notfound.php;

        location ~ \.php$  {
          try_files $uri =404;
          include fastcgi_params;
          fastcgi_pass unix:/run/php/php7.0-fpm.sock;
          fastcgi_split_path_info ^(.+?\.php)(/.*)?$;
          fastcgi_connect_timeout         300; 
          fastcgi_send_timeout           3600; 
          fastcgi_read_timeout           3600;
          fastcgi_buffer_size 128k;
          fastcgi_buffers 4 256k;
          fastcgi_busy_buffers_size 256k;
          fastcgi_temp_file_write_size 256k;
          fastcgi_intercept_errors on; 
          fastcgi_index index.php;
          fastcgi_param SCRIPT_FILENAME /home/site/wwwroot$fastcgi_script_name;
        }

        #cache static files
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|svg+xml)$ {
          expires max;
          log_not_found off;
        }
    }
}

Custom-header-test按照预期出现,其值为Value

X-Cache-Status另一方面,它没有出现在任何请求中,这是为什么?我怎样才能让它出现?

答案1

发生这种情况是因为 nginxadd_header 移除当您尝试设置的值为空时,指定的标头。并且$upstream_cache_status始终为空,因为您从未将请求传递给upstream

要填充此变量,您必须将请求传递给一个命名的upstream。 例如:

upstream php {
    server unix:/run/php/php7.0-fpm.sock;
}

upstream必须在http块内,任何块之外server

然后您可以将 PHP 请求传递给该上游,即:

fastcgi_pass php;

当然,您似乎没有定义fastcgi_cache,或者如果您有定义,它没有显示在您的问题中,所以我希望您在实际设置缓存之前不会得到任何东西。

相关内容