You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多次级域名301重定向配置求助:主域名HTTPS+WWW跳转验证

Apache 301重定向配置优化问题

需求

  • 将多个次级域名通过301重定向至主域名www.example.com
  • 主域名强制跳转至HTTPS且带WWW前缀

已尝试的两种配置

第一种配置

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

问题:当次级域名以HTTPS+WWW格式访问时,无法触发跳转。

第二种配置

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Redirection number 1
RewriteCond %{HTTP_HOST} ^www.example1.com [NC]
RewriteRule ^/?(.*) https://www.example.com/$1 [L,R=301]

#Redirection number 2
RewriteCond %{HTTP_HOST} ^www.example2.com [NC]
RewriteRule ^/?(.*) https://www.example.com/$1 [L,R=301]

#Redirection number 3
RewriteCond %{HTTP_HOST} ^www.example3.com [NC]
RewriteRule ^/?(.*) https://www.example.com/$1 [L,R=301]

#Redirection number 4
RewriteCond %{HTTP_HOST} ^www.example4.com [NC]
RewriteRule ^/?(.*) https://www.example.com/$1 [L,R=301]

问题:功能正常,但每个次级域名都要单独编写规则,写法过于繁琐,需要更简洁的实现方式。

自写规则验证请求(2022年10月21日更新)

我自己编写了以下规则,帮忙验证是否可行:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example1.com$ [OR]
RewriteCond %{HTTP_HOST} ^example2.com$ [OR]
RewriteCond %{HTTP_HOST} ^example3.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example1.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example2.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example3.com$
RewriteRule (.*)$ https://www.example.com/$1 [R=301,L]

验证结论

这条规则可以实现目标功能,能匹配列出的所有次级域名(带/不带WWW前缀的格式),并通过301重定向到主域名https://www.example.com。

不过可以进一步简化写法,用正则表达式合并匹配规则,减少重复的RewriteCond:

RewriteEngine On
# 匹配所有指定的次级域名(带/不带WWW前缀)
RewriteCond %{HTTP_HOST} ^(www\.)?(example1|example2|example3)\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

# 主域名强制HTTPS+WWW(覆盖主域名被不带WWW或HTTP访问的场景)
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

这样既覆盖了次级域名的重定向需求,也保证主域名始终跳转至HTTPS+WWW格式,写法更简洁高效。

内容的提问来源于stack exchange,提问作者user16770416

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:35:24