【发布时间】:2021-08-08 11:35:06
【问题描述】:
我在服务器上的同一目录中托管了多个域,每个域都重定向到各自的子目录。我还将所有域重定向到 HTTPS 并通过 .htaccess 文件删除 WWW。一切都照原样运行,但代码感觉很笨拙,我相信它可以被简化。任何有关如何执行此操作、如何删除多余内容的提示,我们将不胜感激。
在我看来,我应该能够普遍处理 HTTPS 和非 WWW 部分,然后只需要对域到子目录部分进行个性化处理。请注意,我还将一个域的变体(.com 和 .net 重定向到 .org 地址),但我认为那里不会发生任何简化。
这里有足够的代码来说明我忙碌的小.htaccess 文件中发生的一切:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{SERVER_PORT} 80
# Canonical HTTPS/non-WWW
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
RewriteCond %{HTTP_HOST} ^www\.domainone\.org [NC]
RewriteRule (.*) https://domainone.org/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^(ww+\.)?domainone\.org
RewriteCond %{REQUEST_URI} !/domainone-org/
RewriteRule ^(.*)$ /domainone-org/$1 [L]
RewriteCond %{HTTP_HOST} ^www\.domaintwo\.com [NC]
RewriteRule (.*) https://domaintwo.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^(ww+\.)?domaintwo\.com
RewriteCond %{REQUEST_URI} !/domaintwo-com/
RewriteRule ^(.*)$ /domaintwo-com/$1 [L]
RewriteCond %{HTTP_HOST} ^(www\.)?domainthree\.net$ [OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domainthree\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domainthree\.org [NC]
RewriteRule (.*) https://domainthree.org/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^(ww+\.)?domainthree\.org
RewriteCond %{REQUEST_URI} !/domainthree-org/
RewriteRule ^(.*)$ /domainthree-org/$1 [L]
我无法让 RewriteCond %{HTTP_HOST} ^www\. [NC] 在 IfModule 部分工作。这就是为什么每个域下面都有一些看起来像冗余的代码:
RewriteCond %{HTTP_HOST} ^www\.domainone\.org [NC]
RewriteRule (.*) https://domainone.org/$1 [L,R=301]
如果我尝试在 IfModule 中将 HTTPS 和非 WWW 作为两个单独的重写处理(参见下面的代码),那么重定向会中断,并且我在 Google Chrome 窗口中收到“重定向过多”错误。
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
感谢您的帮助。
【问题讨论】:
标签: .htaccess redirect mod-rewrite https url-rewriting