当前,我在LAMP系统上运行带有apache的小型Web服务器。我已经为我的域创建了https证书。现在,我想将任何子域和该子域的目录重写为https,而无需www。我的.htaccess文件中已经有一个代码,它将www版本重写为非www和https。
这是我的.htaccess文件(位于apache根目录中)中的代码:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
我已经尝试过将“ www”与“(。*)”交换,但是我不确定“%1”和“ $ 1”的作用,因为我在互联网上找到了该代码,并且他们没有解释。我研究了正则表达式,但找不到任何东西。
答案 0 :(得分:1)
RewriteEngine On
RewriteBase /
# domain starts with www (change yourdomain to your domain name)
# adding the domain name will ensure its not trying to capture a subdomain with www
# For example: ^www\.(.*)$ will redirect www.subdomain.domain.com to https.
RewriteCond %{HTTP_HOST} ^www\.(yourdomain) [NC]
# then redirect to HTTPS
RewriteRule ^(.*)$ https://%1/$1 [L,R=301]
# check if HTTPS is not being used
RewriteCond %{HTTPS} off
# and because we already redirect www. we exclude it
RewriteCond %{HTTP_HOST} !^www\. [NC]
# and now we test to see if its a subdomain (change yourdomain to your domain name)
RewriteCond %{HTTP_HOST} ^[^\.]+\.yourdomain [NC]
# now we finally redirect it
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]
一旦确认子域重定向有效,就将R=302
更改为R=301
,其原因是为了避免浏览器在确保其正常工作之前缓存重定向。
如果您在使用R=301
时犯了一个错误,则重定向将被缓存,并且在您清除浏览器或使用其他浏览器之前,结果在您的浏览器中可能并不可靠。
%1
用于从RewriteCond
捕获内容,而$1
是从RewriteRule
捕获内容。
如果您有任何结果导致多个值,则数字表示捕获的值索引,如下面的$1
和$2
所示。
在使用#
进行注释时,请确保它们始终位于换行符而不是规则的末尾,否则它将无法正常工作。