使用 fastcgi 缓存时在 NGINX 中添加安全性 headers

add security headers in NGINX while using fastcgi caching

我正在使用带有 fastcgi 缓存的 nginx。我想在我的网站上使用安全 headers。我已经在我的虚拟主机配置中添加了 add header 字段但是我无法获得任何 headers 除非我在我的 [=] 中禁用 add_header X-fastcgi 缓存 $upstream 缓存状态18=] 文件。 虚拟主机文件:

    }
   include /etc/nginx/bots.d/blockbots.conf;
   include /etc/nginx/bots.d/ddos.conf;
   include /etc/nginx/skip_cache.conf ;
   include /etc/nginx/purge_location.conf ;
   include /etc/nginx/gzip_location.conf ;
   include /etc/nginx/security_wp.conf;
        add_header Referrer-Policy 'origin';
        add_header "X-Frame-Options: sameorigin" always;
    location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass  unix:/var/run/php/php7.3-fpm.sock;
    include "/etc/nginx/customfastcgi" ;
    proxy_connect_timeout 300;
    proxy_send_timeout 300;
    proxy_read_timeout 300;
    send_timeout 300;
#    underscores_in_headers on;
client_max_body_size 256M;
    include /etc/nginx/fastcgi_main.conf ;
    }

}

FASTCGI_main.conf

        fastcgi_no_cache $skip_cache;
        fastcgi_cache phpcache;
        fastcgi_cache_valid 200 1m;
        fastcgi_cache_valid 301 1m;
        fastcgi_cache_valid 302 1m;
        fastcgi_cache_valid 307 1m;
        fastcgi_cache_valid 404 1m;
        fastcgi_cache_use_stale error timeout invalid_header http_500 http_503;
        fastcgi_cache_min_uses 1;
        fastcgi_cache_methods GET HEAD;
        fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
       add_header X-FastCGI-Cache $upstream_cache_status;
    ```

RESULT:
curl -I https://dev-kuhicbury.$domain
HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 09 Oct 2020 11:39:35 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
rel="https://api.w.org/"
X-FastCGI-Cache: HIT

您遇到了 add_header 指令的一个非常常见的配置陷阱。 与 NGINX 中的所有其他 array-like 指令类似,如果当前上下文中没有其他 add_header,则它 继承。

典型的解决方案是copy-paste(通过不可避免的重复),在特定位置需要headers:

FASTCGI_main.conf中:

        fastcgi_no_cache $skip_cache;
        fastcgi_cache phpcache;
        fastcgi_cache_valid 200 1m;
        fastcgi_cache_valid 301 1m;
        fastcgi_cache_valid 302 1m;
        fastcgi_cache_valid 307 1m;
        fastcgi_cache_valid 404 1m;
        fastcgi_cache_use_stale error timeout invalid_header http_500 http_503;
        fastcgi_cache_min_uses 1;
        fastcgi_cache_methods GET HEAD;
        fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
        add_header X-FastCGI-Cache $upstream_cache_status;
        add_header Referrer-Policy 'origin';
        add_header "X-Frame-Options: sameorigin" always;

NGINX 这种不直观的行为一直是许多人的麻烦。

这里有一些感兴趣的模块,它们解决了同样的问题(如“更好的 add_header”):