Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

https redirect for rails app behind proxy?

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...