简体   繁体   English

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

[英]https redirect for rails app behind proxy?

server declaration in my nginx.conf: 我的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;
          }
     }

upstream declaration in nginx.conf: nginx.conf中的上游声明:

upstream upstreamy {
    server unix:/var/www//myapp/shared/sockets/unicorn.sock fail_timeout=0;
}

this works fine, myapp is reachable as https://somehost 这工作正常,myapp可以访问为https:// somehost

but the app is generating http url's for redirects, so for instance when authenticating with devise, the / is redirected to http://somehost/user/sign_in instead of https (from the viewpoint of the rails app, it's all http anyway). 但该应用程序正在为重定向生成http url,因此例如在使用devise进行身份验证时,/会被重定向到http:// somehost / user / sign_in而不是https(从rails应用程序的角度来看,无论如何都是http)。

I tried 我试过了

proxy_pass https://upstreamy;

but that just tries to encrypt traffic between nginx and the unicorns that run the rails app. 但这只是试图加密nginx和运行rails app的独角兽之间的流量。

I also tried, in application_helper.rb: 我也试过,在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

but it seems to not work. 但似乎行不通。

How would one solve this? 如何解决这个问题?

Edit: so, the goal is not to make the rails app to require ssl, or to be forced to use ssl; 编辑:所以,目标不是让rails应用程序需要ssl,或者强制使用ssl; the goal is to make the rails app generate https:// urls when redirecting... (I think all other urls are relative). 目标是让rails应用程序在重定向时生成https:// urls ...(我认为所有其他网址都是相对的)。

You need to add the following line: 您需要添加以下行:

proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Proto https;

as in 如在

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;
      }
 }

You can pass :protocol => "https" , to redirect_to. 您可以将:protocol => "https"传递给redirect_to。

You can set this as a default by adding the following to application.rb 您可以通过将以下内容添加到application.rb来将其设置为默认值

Rails.application.routes.default_url_options[:protocol]= 'https'

Reference: https://stackoverflow.com/a/6101147/446203 参考: https//stackoverflow.com/a/6101147/446203

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM