重定向到非 www 不适用于 https 中的页面

Redirect to non www is not working for pages in https

我正在尝试使用 .htaccess 添加重定向规则以实现此类目标:

  1. 将所有 http 页面重定向到 https。
  2. 将所有 www http 和 https 页面重定向到非 www https。

我的 .htaccess 代码:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/ [R=301,L]

一切正常,除了一个:

但是https://www.example.com/1/page.html does not redirect to https://example.com/1/page.html(两个页面都打开)

有什么问题?如何编写 .htaccess 规则将所有页面重定向到 https 非 www?

您可以使用它删除 www 并强制 https:

RewriteEngine on

RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://example.com%{REQUEST_URI} [R=301,L,NE]

确保在测试之前清除缓存。结合这两个规则也有助于加快您的网站速度,而不必 运行 两个单独的规则。