![htaccess 中有一个或多个重写规则](https://linux22.com/image/702156/htaccess%20%E4%B8%AD%E6%9C%89%E4%B8%80%E4%B8%AA%E6%88%96%E5%A4%9A%E4%B8%AA%E9%87%8D%E5%86%99%E8%A7%84%E5%88%99.png)
我有一个主域名和几个附加域名,最近启用了 HTTPS。这对我来说没问题,但我想听听您的意见:
## All http requests to the relative https url
RewriteCond %{SERVER_PORT} 80 [OR]
## redirect the other domains and the non www main main domain
RewriteCond %{HTTP_HOST} ^domain3.com [OR]
RewriteCond %{HTTP_HOST} ^www.domain3.com [OR]
RewriteCond %{HTTP_HOST} ^domain2.com [OR]
RewriteCond %{HTTP_HOST} ^www.domain2.com [OR]
RewriteCond %{HTTP_HOST} ^maindomain.com
## this stuff is for SSL
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
## i send them all to the https main domain
RewriteRule ^(.*)$ https://www.maindomain.com/$1 [L,R=301]
对每个条件都设置重写规则是否是更好的方法?
答案1
当然不需要多个RewriteRule
指令。这只会使事情复杂化并且效率降低。如果您有多个规则(针对每个条件),那么即使您已经位于规范协议 + 主机,每个规则至少都会被处理。
然而,你似乎正在重定向每一个其他域。一切不是 www.maindomain.com
。如果是这样的话,那么你可以简化这条规则,并取消多个状况。 例如:
## All http requests to the relative https url
RewriteCond %{SERVER_PORT} 80 [OR]
## redirect all the other non-canonical domains
RewriteCond %{HTTP_HOST} !^www\.maindomain\.com
## this stuff is for SSL
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
## i send them all to the https main domain
RewriteRule (.*) https://www.maindomain.com/$1 [L,R=301]
因此,现在说的是...如果是 HTTP 则www.maindomain.com
重定向到 HTTPS 和www.maindomain.com
。您无需专门检查每个非规范主机,只需检查它是否不是规范主机即可。
如果您要捕获整个 URL 路径,则不需要开始和结束锚点。即(.*)
与 相同^(.*)$
。
或者,你可以避免使用正则表达式捕获而只需使用REQUEST_URI
服务器变量(值得注意的是,该变量以斜杠开头)。例如:
RewriteRule ^ https://www.maindomain.com%{REQUEST_URI} [L,R=301]
## this stuff is for SSL RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
这看起来像是 cPanel 之前自动注入的疖子每一个 RewriteRule
更新 SSL 证书时。如果其中包含大量RewriteRule
指令,.htaccess
则会导致.htaccess
文件非常臃肿。(它还可能暴露之前不明显的漏洞。)我不知道他们为什么不在文件开头将这些条件分成一个块,然后取反(即反转)它们?例如:
# START: this stuff is for SSL
RewriteCond %{REQUEST_URI} ^/[0-9]+\..+\.cpaneldcv$ [OR]
RewriteCond %{REQUEST_URI} ^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^ - [L]
# END: this stuff is for SSL
## All http requests to the relative https url
RewriteCond %{SERVER_PORT} 80 [OR]
## redirect all the other non-canonical domains
RewriteCond %{HTTP_HOST} !^www\.maindomain\.com
## i send them all to the https main domain
RewriteRule (.*) https://www.maindomain.com/$1 [L,R=301]