HSTS 和重定向

HSTS and redirection

我在此处测试我的网站 https://hstspreload.org,但出现此错误:

Error: HTTP redirects to www first

http://example (HTTP) should immediately redirect to https://example (HTTPS) before adding the www subdomain. Right now, the first redirect is to https://www.example. The extra redirect is required to ensure that any browser which supports HSTS will record the HSTS entry for the top level domain, not just the subdomain.

据我所知,要使重定向有效,应该这样做:

  1. http://example(这是用户在地址栏中输入的内容)
  2. https://example(第一次重定向,到 HTTPS)
  3. https://www.example(第二次重定向,到子域 www)

目前,这是我的 htaccess 导致重定向的代码:

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/ [R,L]

是否possible/advisable在这里插入另一个重定向?有没有风险?

感谢任何 comment/advice/suggestion/rotten-tomato :-)

评论汇总:

  • httpd.conf 和 .htaccess 中的配置从上到下读取。
  • 对于 RewritRules,它们按顺序应用,从上到下,直到到达最后一个。应用符合条件的所有规则。
  • 为防止这种情况,您可以[L] 标记添加到 RewriteRule。这个标签告诉 Apache,如果它符合条件,它就是最后应用的规则。此请求将忽略所有其他规则。

这里重写的顺序是:

  1. 客户请求http://example.com
  2. A RewriteRule 将客户端重定向到 https://example.com
  3. 客户返回https://example.com
  4. 第二个 RewriteRule 将客户端重定向到 https://www.example.com
  5. 客户返回https://www.example.com
  6. 不适用 Rewriterule,Apache 响应请求。

为什么要这样做?它涵盖了所有情况。如果客户端的第一个请求已经是 https://example.com,上面的场景将从第 4 步开始。

示例配置如下所示:

Listen *:80
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com

    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    [... OTHER CONFIGURATION ...]
</VirtualHost>

Listen *:443
<VirtualHost *:443>
    ServerName example.com
    ServerAlias www.example.com

    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    [... OTHER CONFIGURATION ...]
</VirtualHost>