Nginx无法正确地将请求协议转发到上游

bla*_*lip 14 ruby-on-rails nginx forward

我有一个rails 4 beta的网站.它在Nginx + Unicorn上运行.我希望nginx将请求协议('http'或'https')转发给unicorn,以便我可以使用它们.但是我无法使其发挥作用.

我把<%= request.ssl? %><%= request.protocol %>在测试视图文件.我的nginx服务器配置文件如下:

upstream unicorn {
  server unix:/tmp/unicorn.blog.sock fail_timeout=0;
}

server {
  listen 80;
  listen 443;
  server_name example.com;
  root /home/example;

  ssl on;
  ssl_certificate /etc/nginx/ssl/server.crt;
  ssl_certificate_key /etc/nginx/ssl/server.key;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @unicorn;

  location @unicorn {
    proxy_set_header X-Forwarded-Proto https;  # <--- Line 1
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Ssl on;       # <--- Line 2
    proxy_redirect off;
    proxy_pass http://unicorn;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}
Run Code Online (Sandbox Code Playgroud)

我发现我标记的2行不正常.这是我的测试结果:

=================

第1行注释掉,第2行也注释掉了:

访问http://the.url

<%= request.ssl? %>     : false
<%= request.protocol %> : http
Run Code Online (Sandbox Code Playgroud)

访问https://the.url

<%= request.ssl? %>     : false
<%= request.protocol %> : http
Run Code Online (Sandbox Code Playgroud)

=================

第1行注释掉,第2行不是OR行2注释掉,第1行不是OR也没有注释掉

访问http://the.url

<%= request.ssl? %>     : true
<%= request.protocol %> : https
Run Code Online (Sandbox Code Playgroud)

访问https://the.url

<%= request.ssl? %>     : true
<%= request.protocol %> : https
Run Code Online (Sandbox Code Playgroud)

=================

也就是说,如果出现这两行中的一行,则无论实际协议是什么,nginx都会向上游转发"https".但如果这两行中没有一行出现,无论实际协议是什么,nginx都会将"http"转发给上游.

请有人告诉我如何编写nginx配置文件,以便它可以正确转发协议?非常感谢你.

yeg*_*gle 37

尝试:

proxy_set_header X-Forwarded-Proto $scheme;
Run Code Online (Sandbox Code Playgroud)

要么

server {
    Listen 80
    ...
}
server {
    Listen 443
    ...
    location @unicorn {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Ssl on;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,第一种方法工作得很好(当添加到`location @ unicorn`块时),但我只是_only_关注该方案(在我的Rails应用程序中正确构建URL). (2认同)