在服务器上配置仅使用HTTPS通信的教程

2019-10-14 11:18:23于丽

服务器开启 HSTS 的方法是,当客户端通过HTTPS发出请求时,在服务器返回的 HTTP 响应头中包含 Strict-Transport-Security 字段。非加密传输时设置的HSTS字段无效。
在 Apache2 中设置 HSTS

编辑你的 apache 配置文件(如 /etc/apache2/sites-enabled/website.conf 和 /etc/apache2/httpd.conf ),并加以下行到你的 HTTPS VirtualHost:

     # 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 配置文件(例如:/etc/lighttpd/lighttpd.conf):

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

重启 Lighttpd。失效时间也是两年。
Nginx

Nginx 甚至更简单,将下述行添加到你的 HTTPS 配置的 server 块中:

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