# WordPress（或其他各种应用）启用HSTS

**URL:** <https://forum.rainyun.com/t/topic/5358>\
**Category:** 云服务器 RCS\
**Created:** [2023 年9 月 19 日 14:27 UTC](https://forum.rainyun.com/t/topic/5358 "2023-09-19T14:27:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![hhjmk](https://forum.rainyun.com/user_avatar/forum.rainyun.com/hhjmk/32/11397_2.png) [@hhjmk](https://forum.rainyun.com/u/hhjmk)\
发布日期： [2023 年9 月 19 日 14:27 UTC](https://forum.rainyun.com/t/topic/5358/1 "2023-09-19T14:27:42Z")

</div>

[https://www.biliwind.com/805.html](https://www.biliwind.com/805.html)

如果您的Web服务器没有在下面列出，可以使用PHP方法（所有服务器及任何通过PHP编写的Web程序通用）

- [Apache2](https://www.biliwind.com/805.html#apache2)
- [Nginx](https://www.biliwind.com/805.html#nginx)
- [Lighttpd](https://www.biliwind.com/805.html#lighttpd)
- [PHP（通用）](https://www.biliwind.com/805.html#php)

下列配置方法都需要修改配置文件（PHP方法除外），如果你找不到需要的配置文件且使用了宝塔面板，那么请直接在面板中按照以下方式寻找：

软件商店-你的web服务器-设置-配置修改

## Apache2 配置 HSTS

编辑你的 apache 配置文件（如 /etc/apache2/sites-enabled/website.conf 和 /etc/apache2/httpd.conf ），并加以下行到你的 HTTPS VirtualHost：

```auto
# Apache需加载mod_header库，一般位于httpd.conf文件，搜索mod_headers并取消注释。（已加载可跳过）
LoadModule headers_module modules/mod_headers.so #然后对应站点VirtualHost里面插入HSTS响应头信息
 
Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"

```

保存 Apache 配置文件，然后重启。现在你的 web 站点在每次访问时都会发送该请求头，失效时间是两年（秒数），这个失效时间每次都会设置为两年后。

## Nginx 配置 HSTS

Nginx 服务器中的配置最为简单，只需要编辑 Nginx 配置文件（如：/usr/local/nginx/conf/nginx.conf）将下面行添加到你的 HTTPS 配置的 server 块中即可：

```auto
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";

```

如果你发现直接添加在 server 块中无效的情况，你可以试试直接插入到 location ~ \*php 内：

```auto
location ~ [^/]\.php(/|$) {
	add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
}

```

配置保存后重启 Nginx 服务。

## Lighttpd 配置 HSTS

将以下配置增加到你的 Lighttpd 配置文件（例如：/etc/lighttpd/lighttpd.conf）：

```auto
server.modules += ( "mod_setenv" )
$HTTP["scheme"] == "https" {
	setenv.add-response-header = ( "Strict-Transport-Security" => "max-age=63072000; includeSubdomains; preload")
}

```

编辑保存后记得重启一下。

## PHP通用配置 HSTS 方法

将以下代码添加到网站根目录或主题的 index.php 中或者header.php中（建议优先选择修改子主题的header.php）

```auto
header("Strict-Transport-Security: max-age=63072000; includeSubdomains; preload");

```

开启了HSTS后，你部署SSL/TLS的服务检测得分就可能是A+以上了。ssllabs官网以及演示如下：

1. 官网：[https://www.ssllabs.com/](https://www.ssllabs.com/)
2. 中文版：[https://myssl.com](https://myssl.com/)
3. 测试地址：[https://www.ssllabs.com/ssltest/analyze.html](https://www.ssllabs.com/ssltest/analyze.html)

至此配置完毕，您还可以选择加入HSTS Preload List让浏览器直接认为您的网站是启用了HSTS的，从而自动转换成HTTPS。

> [加入HSTS Preload List](https://www.biliwind.com/807.html)
