![](/img/trans.png)
[英].htaccess how to handle dynamic sub-domain redirect to https and no sub-domain to www
[英]Stop WWW for sub-domain with htaccess
我的subdomain.example.com
重定向到www.subdomain.example.com
。
訪問代碼:
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
我在尋找
example.com
至www.example.com
anything.example.com
到anything.example.com
我怎樣才能解決這個問題?
更新:我對子域和根域都使用一個 htaccess 文件,出於某種原因,我不能為不同的域使用單獨的 htaccess 文件。
注意:請不要將此問題標記為重復。 我已經搜索了 stackoverflow 的其他部分,但沒有找到可行的解決方案。
您需要限制重寫條件以僅匹配頂級域:
# ensure www. to top level domain only
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
確保在測試前清除瀏覽器緩存。
備查:
# ensure www. to top level domain only
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
解決方案: https://stackoverflow.com/a/35285128/4643961
### START WWW & HTTPS
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# remove www if subdomain
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.[^.]+\.[^.]+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
選擇:
### START WWW & HTTPS
# add www if not subdomain
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# remove www if subdomain
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.[^.]+\.[^.]+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.