Redirecting a http request to https in Rails

December 2, 2008
Fuad

In my previous blog i instructed how to install a SSL certificate in server. In this tutorial I will provide you some insights on how to redirect a http request to a https.

We need two methods:

1. One is for going to from http to https:

def require_https
redirect_to :protocol => "<a href="https://%22/">https://"</a> unless (request.ssl? or local_request? or request.post? or ENV["RAILS_ENV"]=="development")
end

2. The other is the reverse of this one, that is going from https to http:

def require_http
redirect_to :protocol => "<a href="http://%22/">http://"</a> if (request.ssl?)
end

Now you can call these two function where it is necessary like:

before_filter :require_https

In this point you may get an error like “Infinite Redirection loop”. In order to solve this problem add the following line at

RequestHeader set X_FORWARDED_PROTO 'https'

So the config file should be something like this:

<virtualhost *:443="">
RequestHeader set X_FORWARDED_PROTO 'https'
SSLEngine on
SSLCertificateFile /etc/apache2/SSL_Files/abc.crt
SSLCertificateKeyFile /etc/apache2/SSL_Files/abc.key
SSLCertificateChainFile /etc/apache2/SSL_Files/gd_bundle.crt
</virtualhost>

Now any request coming to http should be redirected to https.

Hope this will serve your purpose. Happy coding!!

Contributor: Fuad Bin Omar, COO, Nascenia

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.