nginx添加Set-Cookie属性Secure和HttpOnly

一、问题:

在https环境中,等保要求为 set-cookie增加secure属性(为了安全,防止http请求时使用此cookie)

二、解决办法1:

在nginx配置文件中可以使用proxy_cookie_path属性实现,该属性可以修改response set-cookie的path属性。如下:

proxy_cookie_path / "/; Path=/; Secure; HttpOnly";

注意:必须原来的set-cookie中有Path=/属性,上面代码才能生效。代码的意思是:Path=/的值/替换成/; Path=/; Secure; HttpOnly

完整的location代码:

location / {
               proxy_store off;
               proxy_redirect  off;
               proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
               proxy_set_header X-Real-IP $remote_addr;
               proxy_set_header Host $http_host;
               client_max_body_size    1000m;
              proxy_pass http://aaa_shengchan_http;
              proxy_connect_timeout 600;
              proxy_send_timeout 600;
              proxy_read_timeout 600;
              add_header  Nginx-Cache "$upstream_cache_status";
              proxy_cookie_path / "/; Path=/; Secure; HttpOnly";
     }

修改完结果:

 

三、解决办法2

使用Headers More模块中的more_set_headers指令

直接修改header的值,简单粗暴:

more_set_headers 'Set-Cookie: $sent_http_set_cookie; secure';

 

但是headers_more模块需要单独安装。该模块主要有4个指令:

  • more_set_headers 用于 添加、修改、清除 响应头
  • more_clear_headers 用于 清除 响应头
  • more_set_input_headers 用于 添加、修改、清除 请求头
  • more_clear_input_headers 用于 清除 请求头

 

nginx增加headers_more模块参考:https://blog.csdn.net/qinxu0611/article/details/104231142?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&dist_request_id=890ec0c1-c03e-47cc-8dfb-51813c12b9a0&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control

已安装完的nginx添加新模块参考:https://blog.csdn.net/hqy860822/article/details/86540094

 

四、其他:

proxy_cookie_path相似的属性还有

1、proxy_cookie_domain:作用是转换response的set-cookie header中的domain选项,由后端设置的域名domain转换成你的域名replacement,来保证cookie的顺利传递并写入到当前页面中,注意proxy_cookie_domain负责的只是处理response set-cookie头中的domain属性,仅此而已

2、proxy_cookie_flags:为cookie设置一个或多个标志。该cookie可以包含文本,变量,以及它们的组合。的 secure, httponly, samesite=strict, samesite=lax, samesite=none 参数添加相应的标志。的 nosecure, nohttponly, nosamesite 参数移除对应的标志。(本来想用这个属性的,但是不知道为啥nginx识别不到proxy_cookie_flags属性。

 

nginx官方文档http_proxy_module模块:http://nginx.org/en/docs/http/ngx_http_proxy_module.html


版权声明:本文为sumengnan原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。