这与htaccess force https and redirect www to non-www, but no other subdomains基本上是同一个问题(即,我想配置Apache将所有非HTTPS 和/或&#34; www&#34; URL重定向到HTTPS非www URL),但我想通过虚拟主机而不是<canvas id="canvas"></canvas>
文件配置Apache(因为我读到避免.htaccess
有一些好处)。
使用.htaccess
文件时,我能够得到以下答案:https://stackoverflow.com/a/34333450/1468130但是当我尝试将该答案的配置转移到我的虚拟主机配置时,它无法正常工作; &#34; https://www.domain.com&#34;从未重定向到&#34; https://domain.com&#34;。
我读了.htaccess
和虚拟主机.htaccess
文件之间的差异,发现这个http://tltech.com/info/rewriterule-in-htaccess-vs-httpd-conf/和这个:https://www.digitalocean.com/community/questions/can-you-use-virtual-host-config-conf-to-redirect-www-domain-to-non-www?answer=15129似乎暗示我可以换行.conf
块中的配置,它可以工作。不幸的是,它没有(&#34; https://www.domain.com&#34;仍然永远不会被重定向到&#34; https://domain.com&#34;),所以我想知道是否互联网知道我做错了什么:
<Directory>
我也尝试过配置<VirtualHost *:80>
ServerName domain.com
ServerAlias www.domain.com
ServerAdmin admin@domain.com
DocumentRoot /var/www/domain.com/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory /var/www/domain.com/>
RewriteEngine On
# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]
# match urls that are non https (without the www)
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^(www\.)(.*) [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</Directory>
</VirtualHost>
作为Dusan Bajic在评论中提出的建议,但这也没有效果; <VirtualHost *:443>
仍然无法重定向到https://www.domain.com
:
https://domain.com
同样根据评论,我尝试了上述<VirtualHost *:443>
ServerName domain.com
ServerAlias www.domain.com
ServerAdmin admin@domain.com
DocumentRoot /var/www/domain.com/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLCertificateFile /etc/letsencrypt/live/domain.com/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/domain.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateChainFile /etc/letsencrypt/live/domain.com/chain.pem
<Directory /var/www/domain.com/>
RewriteEngine On
# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]
</Directory>
</VirtualHost>
配置与*:443
配置配对,并将*:80
块更改为仅将HTTP重定向到HTTPS。但是当我这样做时,&#34; www&#34;永远不会被删除。
<Directory>
答案 0 :(得分:3)
知道了!显然,当我使用letsencrypt(certbot)配置SSL时,它会自动创建另一个虚拟主机文件(/etc/apache2/sites-enabled/domain.com-le-ssl.conf
),该文件有domain.com
*:443
虚拟主机的自定义,以及似乎优先于我之前尝试设置的任何*:443
配置。我将以下代码添加到-le-ssl.conf
文件中,现在我的重定向最终适用于我想要的所有情况,使用100%Apache虚拟主机配置:
<Directory /var/www/domain.com/>
RewriteEngine On
# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]
</Directory>