我有一个上游服务器,它经常通过返回“Set-Cookie”响应标头来设置 Cookie。
我想在上游服务器前面有一个 nginx 代理:
Browser => Nginx => Upstream
If the Browser => Nginx
请求有标头X-No-Cookies: true
我想要回复Upstream => Nginx => Browser
不包含Set-Cookie
响应头。如果X-No-Cookies
有任何其他价值,我会撒谎Set-Cookie
未更改地返回响应标头。我无法更改上游服务器的响应标头行为。
目前我的nginx配置如下,具体注意使用proxy_hide_header
指示。我也附和了$proxy_hide_header
变量在X-No-Cookies
响应头。
map $http_x_no_cookies $proxy_hide_header {
default "";
"true" "Set-Cookie";
}
# Homepage
server {
listen 80;
server_name example.com;
location /api {
proxy_pass https://example.com/api;
proxy_hide_header $proxy_hide_header;
add_header "X-No-Cookies" $proxy_hide_header;
}
}
当我使用 cURL 发出请求时:
curl \
http://example.com/api \
-H 'X-No-Cookies: true' \
-I
我收到以下响应标头:
Server: nginx/1.12.2
Date: Thu, 13 Dec 2018 02:26:41 GMT
Content-Type: application/json
Content-Length: 2255
Connection: keep-alive
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Accept,Authorization
Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Expose-Headers: Content-Length
Set-Cookie: foo=bar; Max-Age=2592000; Expires=Sat, 12 Jan 2019 02:26:41 GMT; Path=/; Domain=example.com; Secure
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-No-Cookies: Set-Cookie
每当proxy_hide_header
提供了一个 nginx 变量作为参数,它似乎没有效果。如果我将变量交换为字符串($proxy_hide_header
替代"Set-Cookie"
)我得到了想要的行为 -Set-Cookie
响应头被省略。
Edit:我已经将这个问题的代码推送到GitHub了
- 我原来的(非工作)实现是here
- 伊万·沙茨基的解决方案是here