https重定向为代理后面的rails app?

Ace*_*770 20 https ruby-on-rails nginx proxypass unicorn

我的nginx.conf中的服务器声明:

    listen       1.2.3.4:443 ssl;
    root /var/www/myapp/current/public;
    ssl on;
    ssl_certificate /etc/nginx-cert/server.crt;
    ssl_certificate_key /etc/nginx-cert/server.key;
    location / {
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $http_host;
          proxy_redirect off;

          if (!-f $request_filename) {
            proxy_pass http://upstreamy;
            break;
          }
     }
Run Code Online (Sandbox Code Playgroud)

nginx.conf中的上游声明:

upstream upstreamy {
    server unix:/var/www//myapp/shared/sockets/unicorn.sock fail_timeout=0;
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,myapp可以访问为https:// somehost

但该应用程序正在为重定向生成http url,因此例如在使用devise进行身份验证时,/会被重定向到http:// somehost/user/sign_in而不是https(从rails应用程序的角度来看,无论如何都是http).

我试过了

proxy_pass https://upstreamy;
Run Code Online (Sandbox Code Playgroud)

但这只是试图加密nginx和运行rails app的独角兽之间的流量.

我也试过,在application_helper.rb中:

# http://stackoverflow.com/questions/1662262/rails-redirect-with-https
def url_options
  super
  @_url_options.dup.tap do |options|
  options[:protocol] = Rails.env.production? ? "https://" : "http://"
  options.freeze
end
Run Code Online (Sandbox Code Playgroud)

但似乎行不通.

如何解决这个问题?

编辑:所以,目标不是让rails应用程序需要ssl,或者强制使用ssl; 目标是让rails应用程序在重定向时生成https:// urls ...(我认为所有其他网址都是相对的).

Yos*_*Kim 45

您需要添加以下行:

proxy_set_header X-Forwarded-Proto https;

如在

location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Proto https;
      proxy_redirect off;

      if (!-f $request_filename) {
        proxy_pass http://upstreamy;
        break;
      }
 }
Run Code Online (Sandbox Code Playgroud)

  • 在很多情况下(尽管可能不是你的),使用`proxy_set_header X-Forwarded-Proto $ scheme;'这样你就可以正确地将X-Forwarded-Proto传递给你的上游应用程序了.或https.当负载均衡器处理https时,这尤其有用. (9认同)
  • 惊人的!设置 nginx 可能会非常痛苦。很痛苦... :) (3认同)