Nginx 代理指令

Nginx proxy directives

我正在尝试使用以下 nginx 配置,以便在所有子域之间共享 cookie。不幸的是,nginx 似乎完全忽略了带有 X-Forwarded-For 和 proxy_cookie_domain 的行(没有效果)。知道我做错了什么吗?

server {
    server_name discuss.mysite.com;
    error_log /var/log/nginx/discuss.log;

    location / {
      proxy_pass http://localhost:8080;
      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_cookie_domain ~^(.*)$ "; Domain=.discuss.mysite.com";
    }
}

这是 curl -I:

的输出
HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 25 Mar 2015 18:14:45 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Vary: Accept-Encoding
Status: 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Set-Cookie: destination_url=http%3A%2F%2Fdiscuss.mysite.com%2F; path=/
Set-Cookie: _forum_session=eTZVVGFzNWJDNjdnV0l0SGFlWDF2MDN2VUtQSnZ0NlN2MmVaR3NKR1A3VFB3MUZFVmRhbTlYNmwxS29TaWkvT05rQmtSaFQwbUhUVjNKeDEwV0JNRGc9PS0teXVLQU92YlRWalJ4WnhpTXNzNkxSdz09--1f472148823725a4e1ad45c0c3b48618c6560be3; path=/; HttpOnly
Set-Cookie: __profilin=p%3Dt; path=/
X-Request-Id: 1cb6fc64-f7b9-45d9-9647-94fbedc44345
X-Runtime: 0.367952
X-UA-Compatible: IE=edge

文档说:

Adds the specified field to a response header provided that the response
code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307.

尝试在端口 8080 指令上添加 headers

来源:http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header

你走错了路,因为指令 proxy_set_header 设置了额外的 header from nginx to 后端,不是 from backend+nginx to 你的 curl 客户端;这就是你看不到它们的原因。

有 2 个选项可以发送额外的 header 客户

  • 在后端设置它们
  • 在适当的位置使用 add_header 指令

但是那些 header 将是 'static' 个(从后端发送的除外,您可以在其中根据需要构建它)- 这在使用 cookie 时是不正确的。要正确提供 cookie,您应该使用 ngx_http_userid_module 模块及其指令。

要跨子域共享 cookie,请使用

userid_domain  .mysite.com;
# or ".discuss.mysite.com" for 4-th level of subdomains
userid_path    /;