https redirect for rails app behind proxy?

2019-01-23 03:56发布

问题:

server declaration in my 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:

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

this works fine, myapp is reachable as 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).

I tried

proxy_pass https://upstreamy;

but that just tries to encrypt traffic between nginx and the unicorns that run the rails app.

I also tried, in 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; the goal is to make the rails app generate https:// urls when redirecting... (I think all other urls are relative).

回答1:

You need to add the following line:

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


回答2:

You can pass :protocol => "https", to redirect_to.

You can set this as a default by adding the following to application.rb

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

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