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 => "https://" 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 => "http://" 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:

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

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

Published On: December 2nd, 2008 / Categories: Blog, Ruby on Rails, Technology /