开启 HSTS 很简单,只要在我们网站的响应头里面新增 HSTS 即可,下面分四种环境来简单说明一下。
1、Nginx 服务器
只需要在站点 server 模块内插入如下配置并重启:
- server {
- listen 443 ssl http2;
- server_name zhang.ge;
- # 直接在 server 插入测试居然不生效,最后发现要在 location ~ *php 内插入:
- location ~ [^/]\.php(/|$) {
- add_header Strict-Transport-Security “max-age=63072000; includeSubdomains; preload”;
- # 以下略…
2、Apache 服务器
Apache 如下配置并重启:
- # 先在 Apache 加载 mod_header 库,一般位于 httpd.conf 文件,自行搜索 mod_headers 并取消注释
- LoadModule headers_module modules/mod_headers.so
- #然后在站点 VirtualHost 里面插入 HSTS 响应头信息,比如:
- <VirtualHost *.*.*.*:443>
- Header always set Strict-Transport-Security “max-age=63072000; includeSubdomains; preload”
- </VirtualHost>
3、LigHttpd
将下述配置增加到你的 Lighttpd 配置文件(一般是 /etc/lighttpd/lighttpd.conf)并重启:
- server.modules += ( “mod_setenv” )
- $HTTP[“scheme”] == “https” {
- setenv.add-response-header = ( “Strict-Transport-Security” => “max-age=63072000; includeSubdomains; preload”)
- }
4、通用方法
如果你用的虚拟主机,或者不会折腾 WEB 软件,那么可以采用更简单的通用方法。原理很简单,通过代码来新增响应头即可,这里只分享一下 php 的做法,其他语言自行参考:
将如下代码插入到网站根目录的 index.php 即可:
- header(“Strict-Transport-Security: max-age=63072000; includeSubdomains; preload”);
以上内容整理自@张戈博客