Force SSL using ssl_requirement in Rails 2 app

前端 未结 3 776
耶瑟儿~
耶瑟儿~ 2020-12-03 03:27

I have a Rails application which need to run under SSL. I tried ssl_requirement but seems I have to type in all the actions in every controllers.

Is there any method

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 03:45

    Use a Rack Middleware.

    # lib/force_ssl.rb
    class ForceSSL
      def initialize(app)
        @app = app
      end
    
      def call(env)
        if env['HTTPS'] == 'on' || env['HTTP_X_FORWARDED_PROTO'] == 'https'
          @app.call(env)
        else
          req = Rack::Request.new(env)
          [301, { "Location" => req.url.gsub(/^http:/, "https:") }, []]
        end
      end
    end
    
    # config/environment.rb
    config.middleware.use "ForceSSL"
    

提交回复
热议问题