Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm looking to learn how to cleanup my app's URLs. My app is powered by Rails 3 on Heroku.

The desired URL is https://www.example.comite.com

I'd like to redirect all URLs unlike the above to that URL. Is this a Rails thing or DNS?

Bad URLs:

https://example.comite.com http://www.example.comite.com http://example.comite.com 

And if anything is trailing, like http://www.example.comite.com/photo/1 for the url to be redirected with the path: https://www.example.comite.com/photo/1

like image 858
AnApprentice Avatar asked Dec 01 '10 21:12

AnApprentice


People also ask

How do I redirect in rails?

Rails's redirect_to takes two parameters, option and response_status (optional). It redirects the browser to the target specified in options. This parameter can be: Hash - The URL will be generated by calling url_for with the options.

Is it OK to redirect HTTP to HTTPS?

If you are using the popular Apache Web server, you can easily redirect all traffic from unsecured HTTP to HTTPS. When a visitor goes to your site will be redirected to the secure HTTPS protocol. The server must allow you to use module mod_rewrite, but it's not a problem for most webhosting providers.


2 Answers

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 => "" } 
like image 37
edgerunner Avatar answered Sep 19 '22 22:09

edgerunner


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 
like image 195
Jon Avatar answered Sep 18 '22 22:09

Jon