views:

474

answers:

3

What do I need to do to get traffic to my ruby on rails app to use https? I have a certificate installed and if I manually type in "https://" in the address bar when accessing the site the little lock icon appears, but just manually going to www.example-app.com in my browser sends traffic through http://.

Is there some one-line config or is it more complicated than that? I've never had to deal with SSL before, so excuse me if I sound like I don't know what's going on.

I'm hosting at MediaTemple in a (gs), if that matters or anyone has experience with such a setup.

+2  A: 

Ruby on Rails is an application framework and not a web server. The HTTPS configuration you need to change is in your web server (Apache, nginx, etc) config.

Zepplock
Okay, I knew that much. I guess then I'm curious how to go about changing that setting. Where would that be? At least its a research lead. I'll poke around apache and mongrel config files.
Austin Fitzpatrick
you don't need to change mongrel. Only Apache config file. I think the default config file contains HTTPS config but it is disable by default. Also look into using nginx web server (uses less resources, easier to configure).
Zepplock
+8  A: 

Check out the ssl_requirement gem.

It lets you specify in your controllers which actions should be served over https and which actions can be served over https. It will then take care of redirecting from http to https and vice-versa.

From the documentation:

class ApplicationController < ActiveRecord::Base
  include SslRequirement
end

class AccountController < ApplicationController
  ssl_required :signup, :payment
  ssl_allowed :index

  def signup
    # Non-SSL access will be redirected to SSL
  end

  def payment
    # Non-SSL access will be redirected to SSL
  end

  def index
    # This action will work either with or without SSL
  end

  def other
    # SSL access will be redirected to non-SSL
  end
end
jerhinesmith
Thanks! Anyone who's looking into this and is also hosting with MediaTemple on a (gs) will want to read this, too: http://kb.mediatemple.net/questions/252/%28gs%29+Ruby+on+Rails+ssl_requirement+plugin
Austin Fitzpatrick
A: 

It's pretty easy, and you don't need a gem for it. I blogged how to redirect without www in rails here. Redirecting to https is (almost) exactly the same.

class ApplicationController < ActionController::Base
  before_filter :redirect_to_https

  def redirect_to_https
    redirect_to "https://example.com#{request.request_uri}" if !request.ssl? && request.host != "localhost"
  end
end

Apply your before_filter on anything that you want to make sure is kept behind the SSL security. I'm usually one for code reuse and gems, but this one is ridiculously simple. Read more about request.protocol.

Jarrett Meyer
Wouldn't this cause issues in a development environment? Unless you also abstract away the example.com part?
jerhinesmith
@jerhinesmith Edited, fixed code sample
Jarrett Meyer