Rails with thin and ssl: http request not auto-redirected to https

*爱你&永不变心* 提交于 2019-12-25 06:47:01

问题


Recently I wanted to secure my rails 4.2.1 app with https the easiest way. I found this question as well as this answer about WEBrick+SSL, both referencing to this post which is unfortunately not reachable any more. Then I found this answer recommending to use thin instead (naming other advantages of using thin). Then I followed this step-by-step guide, finally running thin start --ssl --ssl-key-file .ssl/key.pem --ssl-cert-file .ssl/cert.pem -e production with self-signed certificate. My config/environments/production.rb contains config.force_ssl = true.

Now I would like to access the web normally by typing example.com expecting to be automatically redirected to https://example.com but this does not happen. Typing looong https://example.com works fine. Here is a 2-year-old question with similar issue but any answer doesn't work either and something could have also changed since then.

How can I make it work? Or is there any different recent but simple enough way to start using ssl with rails? Thanks!


回答1:


In your config/environment/production.rb file make sure you have the following:

config.force_ssl = true

Also make sure to update your cookie settings in config/initializers/session_store.rb:

Rails.application.config.session_store :cookie_store, key: '_secure_domain_session', httponly: true, secure: true

You also need to specify secure: true in the config/initializers/devise.rb file if you are using Devise

Also make sure to clear the cache on your browser




回答2:


If you have a load balancer in front of your website that is terminating the TLS/SSL and then connecting via HTTPS to the backend, this would mean the connection from the load balancer to your server is HTTPS, even though the client connection to the load balancer is not. Your load balancer should send the X-Forwarded-Proto header which Rails should take into account.

If you are running Rails under Passenger inside Nginx (or Apache), you may need to configure that to forward the header and/or port.

passenger_set_header X-Forwarded-Proto $http_x_forwarded_proto;
passenger_set_header X-Forwarded-Port $server_port;

Note, however, that Rails looks first at the HTTPS environment variable before it looks at the header, and that might be set to "on" because connection to your web server is HTTPS.

In that case you can redirect all traffic from HTTP to HTTPS inside Nginx:

if ($http_x_forwarded_proto != 'https') {
    rewrite ^ https://$host$uri permanent;
}


来源:https://stackoverflow.com/questions/31755005/rails-with-thin-and-ssl-http-request-not-auto-redirected-to-https

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!