【问题标题】:Forcing HTTPS and www on root domain, but not on subdomains在根域上强制 HTTPS 和 www,但不在子域上
【发布时间】:2022-01-15 07:04:34
【问题描述】:

我想在整个站点中强制使用 HTTPS,这已经完成,以下内容没有问题:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC,NE]

但我还想确保转到顶级域的请求被重定向到 www.example.com

我找到了this answer,但这似乎也会将子域重定向到www? ...或者也许它不会因为子域不使用自己的.htaccess

除了上述之外,我还尝试了以下www. 部分,但它似乎不起作用?

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)|webp$ [NC]
RewriteRule ^ https://www.example.com/%{REQUEST_URI} [R=301,L,NC,NE]

我认为如果它不以 example.com 开头,这会失败,因此会留下任何子域,包括 www

但它似乎根本没有触发。

【问题讨论】:

  • 你清除浏览器缓存了吗?
  • @AmitVerma 是的,我相信是的。
  • 虽然您发布的规则不一定是最佳的,但它们仍然应该“有效”。您的.htaccess 文件中还有哪些其他指令?请包含您完整的.htaccess 文件和这些指令。澄清一下,example.com 确实解析到与 www 子域相同的位置?

标签: regex apache .htaccess mod-rewrite


【解决方案1】:

此配置应该可以满足您的需求:

RewriteEngine On

# When on the root domain (with HTTPs; on "www" or the root domain only):
#  Redirect to WWW Root
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} ^(?!www\.)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]

# When HTTP is off (on "www" or the root domain only)
#  Redirect to the HTTPs Version of the WWW root
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(?:www\.|)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]

您还可以使用this website 测试您的配置。

【讨论】:

  • 太好了 - 谢谢!
猜你喜欢
  • 2015-07-18
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2012-01-01
  • 2014-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多