SSL with Ruby on Rails

前端 未结 4 844
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 22:29

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 accessin

相关标签:
4条回答
  • 2021-01-31 22:34

    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
    
    0 讨论(0)
  • 2021-01-31 22:35

    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.

    0 讨论(0)
  • 2021-01-31 22:47

    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.fullpath}" 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. (Note that in the Ruby 1.9.3 / Rails 3.2 environment, the name is request.fullpath; in some earlier versions, it was request.request_uri; see the release notes, etc.)

    0 讨论(0)
  • 2021-01-31 22:59

    https://github.com/bartt/ssl_requirement here is a newer version of ssl_requirement.

    0 讨论(0)
提交回复
热议问题