最近剛剛將一個項目設置為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 = true
config.ssl_options = { hsts: false }
清除Chrome的hsts集
完成配置之后,繼續測試前需要刪除瀏覽器中保存的hsts信息,以Chrome為例,輸入chrome://net-internals/#hsts,在Delete domain中輸入域名,點擊delete刪除即可