.htaccess:将主域重定向到https:// www,子域重定向到https://(不带www)

时间:2017-12-20 09:34:49

标签: .htaccess redirect https dns subdomain

我知道这里提供的.htaccess - 解决方案数量无穷无尽,但没有一个仅针对主域重定向到https www,而是https }} www仅适用于子域名。根据{{​​3}}问题和php解决方案,现在我想修改我的.htaccess文件以满足以下需求。

主域名

  • http重定向到https
  • non-www重定向到www
  • (对于主域名:www 是理想的,应该会出现)

子站点:

  • http重定向到https
  • www重定向到non-www
  • (对于子域名:www 不是,并且应该

我目前的做法是这样的:

RewriteEngine on

# Ensure https for all domains (main- and subdomains):
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Redirect non-www to www only for main domain, but not for subdomains:
RewriteCond %{HTTP_HOST} ^(domain\.com)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]

# Redirect www to non-www only for subdomains:
RewriteCond %{HTTP_HOST} ^(www\.)?subdomain\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://subdomain.domain.com%{REQUEST_URI} [R=301,L,NE]
  • 我认为子域名存在一些错误?
  • 我不理解第一个命令中的RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}部分:当没有https进入子域时,此命令是否将访问者发送到主域?或者{HTTP_HOST}是否已包含可能的子域名?

评论:子域的内容与主域完全不同(可以是 private.website.com cloud.website.com 例如)。它不仅仅是一种不同的语言。因此,通过浏览器源或CMS创建内部转发似乎没有用。它应该通过.htaccess - 仅限条目执行。

1 个答案:

答案 0 :(得分:1)

对于子域部分,规则是重复的,您应该修改为:

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

对于这些规则:

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

第1行:如果https关闭

第2行:对于任何模式,将用户永久重定向到https://%{HTTP_HOST}%{REQUEST_URI}%{HTTP_HOST}是从HTTP request header获取的,当用户发出请求domain.com时,%{HTTP_HOST}domain.com,而此请求subdomain.domain.com为制作完毕后,%{HTTP_HOST}就是subdomain.domain.com