浅析Nginx反向代理cookie配置指令proxy_cookie_domain作用

一、proxy_cookie_domain配置误区

  Nginx做反向代理的时候,我们一般习惯添加proxy_cookie_domain配置,来做cookie的域名转换,比如

location /api {
   proxy_pass https://***.test.com;
   proxy_cookie_domain b.test.com  a.test.com;
}

  最近在项目中发现,不配置这个属性,依然运转正常,我发现自己一直以来可能理解错了这个选项。我们首先来看下proxy_cookie_domain的官方定义:

Syntax: proxy_cookie_domain off;
proxy_cookie_domain domain replacement;
Default:
proxy_cookie_domain off;
Context: http, server, location
This directive appeared in version 1.1.15.

Sets a text that should be changed in the domain attribute of the “Set-Cookie” header fields of a proxied server response. Suppose a proxied server returned the “Set-Cookie” header field with the attribute “domain=localhost”. The directive proxy_cookie_domain localhost example.org will rewrite this attribute to “domain=example.org”.

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

  但是我们知道response在写set-cookie的时候,domain是一个可选项,并不是必填项,所以如果 cookie 里本身就没有 domain 内容,这个时候由于set-cookie本身就没有domain内容,proxy_cookie_domain也就没有必要了,这也是为什么在部分项目中不配置proxy_cookie_domain依然正常的原因。

  但是对于一些设置了domain的项目,比如

  这种情况下当你用nginx做反向代理的时候,就必须要转换一下了。

二、proxy_cookie_domain配置解析

  说到这里,我们再看看之前的错误理解:

“proxy_cookie_domain的作用是实现前后端cookie域名转换,保证顺利传递”

  乍一看好像也没错,但是现在想想,理解还是不够啊,因为proxy_cookie_domain的作用是单向的,并不是双向转换的。我们先看下cookie的传递过程,盗一张图

  浏览器在发送请求的时候,会在request header中带上cookie项(有内容的话),此时的cookie是一个字符串,一个key=value并用分号分割的字符串

  其中并不包含任何域名信息。这是因为浏览器在设置cookie选项的时候,所选取的内容都是缓存中接口域名下的。然后request的只要请求发送出去之后,cookie中有关domain信息其实是不存在的,它只是一个普通的字符串,随便proxy_pass到任何位置,都会正常携带下去。因此在前端到后端的request的过程中,proxy_cookie_domain是没用的

  而server端在做响应的时候,通过set-cookie的domain属性,可以控制cookie的生效域名目标,做到诸如二级域名cookie分离等等,如果前端接收到的set-cookie的domain和当前域名不一致,或者一级域名不一致(二级域名可以共享一级域名下的cookie),这个cookie在后续的通信中就是无效的,所以这里才需要去做domain的转换,也就是说response中set-cookie的domain转换才是有意义的,这也正是proxy_cookie_domain的作用所在。

  当response的set-cookie中domain不去设置时,cookie顺利传入浏览器中,浏览器会自动设置这个cookie的生效域名为当前域名。

三、proxy_cookie_path属性

  和这个类似的还有proxy_cookie_path属性,同样的该属性仅作用在修改response set-cookie的path属性,而一般情况下,用的也比较少。

posted @ 2021-08-21 22:16  古兰精  阅读(3281)  评论(0编辑  收藏  举报