HTTP 严格传输安全(HSTS)是一种安全功能,web 服务器通过它来告诉浏览器仅用 HTTPS 来与之通讯,而不是使用 HTTP。本文会说明如何在 Apache2、Nginx 和 Lighttpd 上如何启用 HSTS。在主流的 web 服务器上测试通过: Nginx 1.1.19、 Lighttpd 1.4.28 和 Apache 2.2.22 ,环境为 Ubuntu 12.04、 Debian 6 & 7 和 CentOS 6,只需要调整部分参数就可以工作在其它的发行版上。
什么是 HTTP 严格传输安全?引用自 Mozilla Developer Network:
以下引自维基百科:
场景举例:
注意,如果你之前没有使用 HTTPS 访问过该站点,那么 HSTS 是不奏效的。网站需要通过 HTTPS 协议告诉你的浏览器它支持 HSTS。
服务器开启 HSTS 的方法是,当客户端通过HTTPS发出请求时,在服务器返回的 HTTP 响应头中包含 在 Apache2 中设置 HSTS
编辑你的 apache 配置文件(如 # Optionally load the headers module: LoadModule headers_module modules/mod_headers.so <VirtualHost 67.89.123.45:443> Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload" </VirtualHost> 现在你的 web 站点在每次访问时都会发送该请求头,失效时间是两年(秒数)。这个失效时间每次都会设置为两年后,所以,明天你访问时,它会设置为明天的两年后。 你只能在 HTTPS 虚拟机中设置这个头,而不能设置在 HTTP 虚拟机中。 要将你的访问者重定向到对应 HTTPS 站点,可使用如下设置: <VirtualHost *:80> [...] ServerName example.com Redirect permanent / https://example.com/ </VirtualHost> 如果仅仅是做重定向的话,甚至不需要设置 DocumentRoot。 你也可以使用 mod_rewrite 来做重定向,但是上述的方式更简单更安全。不过,mod_rewrite 可以重定向页面到对应的 HTTPS 页面,而上述配置则只重定向到“/”: <VirtualHost *:80> [...] <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} </IfModule> </VirtualHost>
不要忘记重启 Apache。 Lighttpd
对于 lighttpd 来说很简单,将下述配置增加到你的 Lighttpd 配置文件(例如: server.modules += ( "mod_setenv" ) $HTTP["scheme"] == "https" { setenv.add-response-header = ( "Strict-Transport-Security" => "max-age=63072000; includeSubdomains; preload") }
重启 Lighttpd。失效时间也是两年。 NginxNginx 甚至更简单,将下述行添加到你的 HTTPS 配置的 server 块中: add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
不要忘记重启 Nginx。 转载请保留固定链接: https://linuxeye.com/security/2411.html |