且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用fastcgi缓存时在NGINX中添加安全标头

更新时间:2023-11-27 16:27:52

您已经踏上 add_header 指令的一个非常常见的配置陷阱.与NGINX中的所有其他类似数组的指令类似,如果当前上下文中没有其他 add_header ,则仅继承 .

You've stepped onto a very common configuration pitfall of the add_header directive. Similar to all other array-like directives in NGINX, it is only inherited, if there is no other add_header in the current context.

典型的解决方案是(通过不可避免的复制)将所需的标头复制粘贴(在不可避免的位置):

The typical solution is to copy-paste (through inevitable duplication), the desired headers in a specific location:

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的这种非直觉行为已成为许多麻烦的根源.

This unintuitive behavior of NGINX has been a source of trouble for many.

以下是一些有趣的模块,它们解决了相同的问题(例如,更好的 add_header "):

Here are some modules of interest, which address the same issue (as in, "better add_header"):

  • ngx_headers_more
  • ngx_security_headers, more applicable to your case