20seven

Devigner blog about development and design

How to Force Https Without a Host in Rails

I needed a quick fix this morning for a rails site that needed to be redirected to the secure site if a request came in on a non-secure url. I didn’t want to nutz with the htaccess or the apache configs and this particular site certificate required that there be no host (www), so I had to strip that out.

Here is how to redirect to a secure connection while maintaining the host:

Add before_filter :redirect_to_ssl to the application controller and add the following:

def redirect_to_ssl
   redirect_to :protocol => "https://" unless (@request.ssl? or local_request?)
end

Here is how I did it to strip the host from the url and force the user to the secure site without the host:

Add before_filter :redirect_to_ssl to the application controller and add the following:

def redirect_to_ssl
   @cont = controller_name
   @act = action_name
   redirect_to "https://sitename.com/#{@cont}/#{@act}/#{params[:id]}" unless (@request.ssl? or local_request?)
end

You don’t have to worry about getting extra forward slashes in your url if you have some default routes setup. This nicely catches any controller/action/id’s if necessary.