Amazon.com Widgets
...not so private reflections of greg.newman
Categories & Search

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.

3 Comments

You could do this:

def redirect_to_ssl
    redirect_to url_for params.merge({:protocol => 'https://'})
end

...if you don't like to stick to the conventional routing formats.

Someone else below asked this already about antispam scripts.
I am getting nailed with Spam on my website mails and in our blog website - now its offline too much spam. Is there anyway to stop this? If not, there really isn't any point in leaving it up and active. Any help will be greatly appreciated.

Thanks for this, a very concise tutorial, just what I was looking for.

Leave a comment