我在我的 Debian 上安装了 certbot,以便将 lets encrypt 证书安装到 apache2。
一切运行顺利,我选择了软件选项将 http 流量重定向到 https。
该软件通过以下方式更改了我的 apache2 conf 文件:
<VirtualHost *:80>
ServerName myweburl.com
ServerAlias www.myweburl.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/myweburl/public
<Directory /var/www/html/myweburl>
Options FollowSymLinks MultiViews
Order Allow,Deny
Allow from all
AllowOverride All
ReWriteEngine On
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
/////////
// The software added these lines
/////////
RewriteCond %{SERVER_NAME} =myweburl.com [OR]
RewriteCond %{SERVER_NAME} =www.myweburl.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
这些行不起作用。
如果我访问 myweburl.com,它不会重定向。
如果我访问 https:// www.myweburl.com,我可以看到正确安装的证书。
答案1
对于当前版本的 Apache,有几种方法可以解决这个问题:
- 尝试使用
%{HTTP_HOST}
而不是%{SERVER_NAME}
例如使用%HTTP_HOST
<VirtualHost *:80>
ServerName myweburl.com
ServerAlias www.myweburl.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/myweburl/public
<Directory /var/www/html/myweburl>
Options FollowSymLinks MultiViews
Order Allow,Deny
Allow from all
AllowOverride All
RewriteEngine on
RewriteCond %{HTTP_HOST} myweburl.com [OR]
RewriteCond %{HTTP_HOST} www.myweburl.com
# RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [END,NE,R=permanent]
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
- 使用
Redirect
。这需要mod_alias被启用。
例如使用Redirect
<VirtualHost *:80>
ServerName myweburl.com
ServerAlias www.myweburl.com
ServerAdmin webmaster@localhost
# DocumentRoot /var/www/html/myweburl/public
Redirect permanent / https://myweburl.com/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
- 使用替代
Rewrite
规则。您可以在此处阅读有关 mod_rewrite 重新映射的更多信息。
例如替代mod_rewrite
规则
<VirtualHost *:80>
ServerName myweburl.com
ServerAlias www.myweburl.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/myweburl/public
<Directory /var/www/html/myweburl>
Options FollowSymLinks MultiViews
Order Allow,Deny
Allow from all
AllowOverride All
RewriteEngine on
RewriteCond %{HTTPS} off
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=permanent]
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>