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

前端 未结 6 699
感动是毒
感动是毒 2020-12-23 16:56

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

6条回答
  •  青春惊慌失措
    2020-12-23 17:34

    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_https
    end
    class TypicalController < ApplicationController
        def blah
        end
    end
    class HomePageController < ApplicationController
        skip_before_filter :redirect_https
    end
    

    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 code above to avoid that complication.

    happy hacking.

提交回复
热议问题