加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Nginx无法将请求协议正确转发到上游

发布时间:2020-12-16 20:06:35 所属栏目:百科 来源:网络整理
导读:我有一个网站在rails 4 beta.它正在Nginx Unicorn上运行.我希望nginx将请求协议(‘http’或’https’)转发到独角兽,以便我可以与他们一起工作.但是我无法使其工作. 我把%= request.ssl? %GT;和%= request.protocol%在视图文件中进行测试.我的nginx服务
我有一个网站在rails 4 beta.它正在Nginx Unicorn上运行.我希望nginx将请求协议(‘http’或’https’)转发到独角兽,以便我可以与他们一起工作.但是我无法使其工作.

我把<%= request.ssl? %GT;和<%= 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;
}

我发现我标记的2条线不正确.这是我的测试结果:

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

第1行评论说,第2行也注释了:

访问http://the.url

<%= request.ssl? %>     : false
<%= request.protocol %> : http

访问https://the.url

<%= request.ssl? %>     : false
<%= request.protocol %> : http

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

第1行注释掉,第2行不是OR
第2行注释掉,第1行不是OR
也不是评论

访问http://the.url

<%= request.ssl? %>     : true
<%= request.protocol %> : https

访问https://the.url

<%= request.ssl? %>     : true
<%= request.protocol %> : https

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

也就是说,如果出现这两行之一,nginx将“https”转发到上游,无论实际协议是什么.但是如果没有出现这两行,nginx会将“http”转发到上游,无论实际的协议是什么.

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

解决方法

尝试:
proxy_set_header X-Forwarded-Proto $scheme;

要么

server {
    Listen 80
    ...
}
server {
    Listen 443
    ...
    location @unicorn {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Ssl on;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读