Apache2 的 Vhost 的配置方式与之前略有不同。
当然传统的配置方式依然是可用的,但使用新的配置方式会更方便一些,提供一些新的功能。
首先,打开 Apache2 的配置目录(通常为/etc/apache2):
cd /etc/apache2
Apache2 将 Vhost 的配置目录拆分成两个:
-
sites-available,存放可用的 Vhost 配置,新建的配置放这里 -
sites-enabled,存放已经使用(已开启的)Vhost 配置
需要将新的 Vhost 配置保存到sites-available目录下,这里以我的网站配置为例:
<VirtualHost *:80> # This first-listed virtual host is also the default for *:80 ServerName www.icexmoon.cn ServerAlias icexmoon.cn DocumentRoot "/var/www/html" ErrorDocument 404 /404.html <Directory "/var/www/html"> RewriteEngine on RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^(.*)?$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R] AllowOverride All Require all granted </Directory> RewriteCond %{SERVER_NAME} =www.icexmoon.cn [OR] RewriteCond %{SERVER_NAME} =icexmoon.cn RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost>
设置好配置文件后需要通过以下命令启用:
sudo a2ensite icexmoon.cn
Apache 会自动根据sites-available目录下的配置在sites-enable目录下生成对应的配置文件。
重新加载配置,以让配置生效:
systemctl reload apache2
这样配置的好处除了可以灵活地启用/禁用 Vhost 配置以外,在为站点申请 SSL 证书时也更方便。
比如:
sudo certbot --apache -d icexmoon.cn -d www.icexmoon.cn
证书工具在下载完证书后会自动在sites-enable和sites-available目录下添加对应的证书配置文件,我们不需要修改原有 Vhost 配置文件,甚至不需要重新加载配置文件或重启 Apache2 服务,SSL 服务就可以正常使用。

文章评论