腾讯云服务器优惠活动华纳云香港服务器

如何为HTTPS站点新增响应头来开启HSTS?

开启 HSTS 很简单,只要在我们网站的响应头里面新增 HSTS 即可,下面分四种环境来简单说明一下。

1、Nginx 服务器

只需要在站点 server 模块内插入如下配置并重启:

  1. server {
  2.     listen 443 ssl http2;
  3.     server_name zhang.ge;
  4.     # 直接在 server 插入测试居然不生效,最后发现要在 location ~ *php 内插入:
  5.     location ~ [^/]\.php(/|$) {
  6.         add_header Strict-Transport-Security “max-age=63072000; includeSubdomains; preload”;
  7.         # 以下略…

2、Apache 服务器

Apache 如下配置并重启:

  1. # 先在 Apache 加载 mod_header 库,一般位于 httpd.conf 文件,自行搜索 mod_headers 并取消注释
  2. LoadModule headers_module modules/mod_headers.so
  3. #然后在站点 VirtualHost 里面插入 HSTS 响应头信息,比如:
  4. <VirtualHost *.*.*.*:443>
  5.     Header always set Strict-Transport-Security “max-age=63072000; includeSubdomains; preload”
  6. </VirtualHost>

3、LigHttpd

将下述配置增加到你的 Lighttpd 配置文件(一般是 /etc/lighttpd/lighttpd.conf)并重启:

  1. server.modules += ( “mod_setenv” )
  2. $HTTP[“scheme”] == “https” {
  3.     setenv.add-response-header  = ( “Strict-Transport-Security” => “max-age=63072000; includeSubdomains; preload”)
  4. }

4、通用方法

如果你用的虚拟主机,或者不会折腾 WEB 软件,那么可以采用更简单的通用方法。原理很简单,通过代码来新增响应头即可,这里只分享一下 php 的做法,其他语言自行参考:

将如下代码插入到网站根目录的 index.php 即可:

  1. header(“Strict-Transport-Security: max-age=63072000; includeSubdomains; preload”);

以上内容整理自@张戈博客

本文地址:https://boke112.com/post/4704.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu