Wednesday, January 5, 2011

Rails and SSL (https://)

Two more caveats:
  • First caveat is that if you want to go back and forth between http and https, you MUST explicitly set all of your routes to have http or https protocol. If you don't, then when rails generates your routes it will just use the protocol of the current page. This is annoying, but I can see why they would do this (if you are looking at something securely, then just look at everything securely).
  • Second caveat is that you must use the route_name_url throughout your application instead of route_name_path, as some are accustomed to. The _url named route gives you the full url (duh), which is what you want if you are on a page using http and want to go to https (whereas _path only gives you the uri, and will use the protocol and host of the current page). If you already use _url, then you are one step ahead in the game
Here is a sample of some of my routes using the protocol option:

# Public routes using http protocol
map.with_options :protocol => "http" do |http|
  http.login '/login',   :controller => 'sessions', :action => 'new'
  http.logout '/logout',  :controller => 'sessions', :action => 'destroy'
  http.resources :users, :sessions, :requirements => {:protocol => "http"}
end

# Public routes using https protocol
map.with_options :protocol => ROUTES_PROTOCOL do |https|
  https.form_step '/form/*slug', :controller => 'forms', :action => 'show'
  https.form_edit '/edit/*path', :controller => 'forms', :action => 'edit'
  https.resources :forms, :requirements => {:protocol => ROUTES_PROTOCOL}
end
http://siannopollo.blogspot.com/2007/08/rails-and-ssl-https.html

1 comment:

Anonymous said...

i'm using 2.3.8 http://www.mysite.com/login

still matches the routes even if i set this with_option protocol = https and requirement => {:protocol => 'https'}