Rails - How to Redirect from http://example.com to https://www.example.com Rails - How to Redirect from http://example.com to https://www.example.com heroku heroku

Rails - How to Redirect from http://example.com to https://www.example.com


As an extension to user2100689's answer, in Rails 3+ you can use config.force_ssl = true in config/environments/production.rb

The line can just be uncommented as follows

# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.config.force_ssl = true


DNS records cannot define the protocol for a domain, therefore you can't redirect http:// to https:// through DNS. Doing it through the web server configuration is not portable, hard to do, error prone and just plain outdated. This is a job best handled by the Rails router.

# beginning of routes.rb match "*path" => redirect("https://www.mysite.com/%{path}"), :constraints => { :protocol => "http://" }match "*path" => redirect("https://www.mysite.com/%{path}"), :constraints => { :subdomain => "" }


Because this is Heroku, you cannot use apache or nginx configs. What you can do is put a before_filter in your ApplicationController, assuming you have 3 or more controllers like these below, although of course they will be in separate files

class ApplicationController < ActionController::Base    def redirect_https                redirect_to :protocol => "https://" unless request.ssl?        return true    end    before_filter :redirect_httpsendclass TypicalController < ApplicationController    def blah    endendclass HomePageController < ApplicationController    skip_before_filter :redirect_httpsend

You may also need to fiddle your routes a bit when using devise, but I suspect that was just the way we did it so I won't get into those details here, and I've modified the codeabove to avoid that complication.

happy hacking.