这与htaccess force https和将www重定向到非www基本上是相同的问题,但是没有其他子域(即,我想配置Apache以将所有非HTTPS和/或“ www” URL重定向到HTTPS非www URL) ,但是我想通过虚拟主机而不是.htaccess
文件来配置Apache (因为我读到避免避免.htaccess
有一些好处)。
使用.htaccess
文件时,我可以获得以下答案:https : //stackoverflow.com/a/34333450/1468130但是,当我尝试将该答案的配置转移到我的虚拟主机配置时,它不起作用。“ https://www.domain.com ”从未重定向到“ https://domain.com ”。
我仔细阅读了.htaccess
虚拟主机.conf
文件和虚拟主机文件之间的区别,并发现了此http://tltech.com/info/rewriterule-in-htaccess-vs-httpd-conf/和以下内容:https : //www.digitalocean.com/社区/问题/您是否可以使用虚拟主机配置-conf-to-redirect-www-domain-to-non-www?answer = 15129,这似乎暗示我可以将配置包装成一个<Directory>
块,然后它会工作。不幸的是,它没有(“ https://www.domain.com ”仍然从未重定向到“ https://domain.com ”),所以我想知道互联网是否知道我在做什么错:
<VirtualHost *:80>
ServerName domain.com
ServerAlias www.domain.com
ServerAdmin [email protected]
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>
我也尝试<VirtualHost *:443>
按照评论中的Dusan Bajic的建议进行配置,但这也没有任何效果。https://www.domain.com
仍然不会重定向到https://domain.com
:
<VirtualHost *:443>
ServerName domain.com
ServerAlias www.domain.com
ServerAdmin [email protected]
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
与将<Directory>
块更改为仅将HTTP重定向到HTTPS的配置配对。但是,当我这样做时,“ www”永远不会被删除。
<Directory /var/www/paradoxmayhem.com/>
RewriteEngine On
RewriteCond %{SERVER_NAME} =www.paradoxmayhem.com [OR]
RewriteCond %{SERVER_NAME} =paradoxmayhem.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</Directory>
知道了!显然,当我使用letencrypt(certbot)配置SSL时,它会自动创建另一个虚拟主机文件(位于/etc/apache2/sites-enabled/domain.com-le-ssl.conf
),该文件具有自己的domain.com
*:443
虚拟主机定义,并且似乎优先于*:443
我尝试设置的任何配置前。我将以下代码添加到-le-ssl.conf
文件中,现在,使用100%Apache Virtual Host配置,重定向最终可以在所有需要的情况下工作:
<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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句