Force SSL using ssl_requirement in Rails 2 app

前端 未结 3 767
耶瑟儿~
耶瑟儿~ 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:43

    You can try test if request is in ssl or not in a before_filter in your application

    class Application < AC::Base
    
      before_filter :need_ssl
    
      def need_ssl
        redirect_to "https://#{request.host}/#{request.query_string}" unless request.ssl?
      end
    end
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-12-03 03:47

    The key problem is that force_ssl.rb isn't being loaded and that lib isn't loaded by default in rails 3.1. You have to add

    config.autoload_paths += %W(#{config.root}/lib)
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    

    to application.rb

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