Rails配置项force_ssl与hsts

来源:互联网 发布:最全家庭网络个人投资 编辑:程序博客网 时间:2024/05/01 01:16

最近刚刚将一个项目设置为HTTP与HTTPS共存,在这过程中对Rails的配置项force_ssl有了更深的理解。

force_ssl是什么

force_ssl是什么呢?我们可以从以下三段Rails Guide中提及的force_ssl配置项信息中找到答案:

config.force_ssl forces all requests to be served over HTTPS by using the ActionDispatch::SSL middleware, and sets config.action_mailer.default_url_options to be { protocol: ‘https’ }. This can be configured by setting config.ssl_options - see the ActionDispatch::SSL documentation for details.

config.force_ssl通过使用中间件ActionDispatch::SSL使所有请求转为HTTPS,同时将config.action_mailer.default_url_options配置为{ protocol: ‘https’ }。这一项可以通过设置config.ssl_options来进行配置。详见ActionDispatch::SSL相关文档。

ActionDispatch::SSL forces every request to be served using HTTPS. Enabled if config.force_ssl is set to true. Options passed to this can be configured by setting config.ssl_options.

ActionDispatch::SSL将所有请求转为HTTPS,可以通过将config.force_ssl设置为true来开启它。其相关选项可以通过设置config.ssl_options来指定。

Sniff the cookie in an insecure network. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN, it is especially easy to listen to the traffic of all connected clients. For the web application builder this means to provide a secure connection over SSL. In Rails 3.1 and later, this could be accomplished by always forcing SSL connection in your application config file:

config.force_ssl = true

不安全网络中的cooie嗅探。无线LAN网是典型的此类网络。在一个未加密的无线LAN网中,很容易监听到网络信息。这就要去网站建设者提供基于SSL的安全链接。在Rails 3.1以后的版本中,可以通过以下设置很容易的强制使用SSL链接。

config.force_ssl = true

force_ssl与hsts

hsts即Strict-Transport-Security,hsts的作用是强制客户端(如浏览器)使用HTTPS与服务器创建连接。即在客户端第一次通过HTTPS获得服务器响应之后,客户端保存了hsts相关的头信息(例如过期时间等),之后的请求会被强制使用HTTPS。

为什么特别说明hsts呢,这是因为在我设置HTTP与HTTPS共存的应用时,这个协议会阻碍我的调试工作:HTTP请求总是被转为HTTPS。

在注意到force_ssl与hsts的关系之前,我首先对Nginx的配置进行了如下检查:
- 同时监听80和443端口,80端口没有被转为HTTPS请求;
- 没有设置hsts头信息

排除了Nginx对HTTP跳转HTTPS的作用,再次检查Rails配置文件。

在rails项目的config/environments/production.rb文件中,可以找到force_ssl配置项:

 # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.  config.force_ssl = true   

注意config.force_ssl的注释:Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
除了上面提及的Force all access to the app over SSL,还有Strict-Transport-Security。
原来在force_ssl设置为true后,Rails默认使用了hsts协议。要禁用它很简单,设置ssl_options为hsts: false即可。

config.force_ssl = trueconfig.ssl_options = { hsts: false }

清除Chrome的hsts集

完成配置之后,继续测试前需要删除浏览器中保存的hsts信息,以Chrome为例,输入chrome://net-internals/#hsts,在Delete domain中输入域名,点击delete删除即可
这里写图片描述
ActionDispatch::SSL文档

0 0
原创粉丝点击