在 Apache2 上配置**多站点(虚拟主机 VirtualHost)**是非常常见的需求。下面以 Ubuntu / Debian 系列为例,从原理到实操一步步说明(CentOS/RHEL 也类似,只是路径略有不同)。
Apache 通过 VirtualHost(虚拟主机) 来区分不同站点,常见区分方式:
下面以基于域名为例。
site1.testsite2.test/var/www/site1/var/www/site2sudo mkdir -p /var/www/site1
sudo mkdir -p /var/www/site2
echo "site1" | sudo tee /var/www/site1/index.html
echo "site2" | sudo tee /var/www/site2/index.html
sudo nano /etc/apache2/sites-available/site1.test.conf
内容:
<VirtualHost *:80>
ServerName site1.test
DocumentRoot /var/www/site1
<Directory /var/www/site1>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/site1_error.log
CustomLog ${APACHE_LOG_DIR}/site1_access.log combined
</VirtualHost>
sudo nano /etc/apache2/sites-available/site2.test.conf
内容:
<VirtualHost *:80>
ServerName site2.test
DocumentRoot /var/www/site2
<Directory /var/www/site2>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/site2_error.log
CustomLog ${APACHE_LOG_DIR}/site2_access.log combined
</VirtualHost>
sudo a2ensite site1.test.conf
sudo a2ensite site2.test.conf
禁用默认站点(可选):
sudo a2dissite 000-default.conf
sudo apache2ctl configtest
sudo systemctl reload apache2
如果你没有真实域名,可以修改本地 hosts 文件:
sudo nano /etc/hosts
C:\Windows\System32\drivers\etc\hosts
添加:
127.0.0.1 site1.test
127.0.0.1 site2.test
浏览器访问:
http://site1.test
http://site2.test
如果你想用不同端口:
Listen 8080
<VirtualHost *:8080>
DocumentRoot /var/www/site2
</VirtualHost>
访问方式:
http://服务器IP:8080
✅ 端口被占用
sudo netstat -tlnp | grep 80
✅ 配置不生效
apache2ctl -S
✅ 403 Forbidden
<Directory> 未配置 Require all granted✅ 403 / 404
sudo chown -R www-data:www-data /var/www
一个站点 = 一个 VirtualHost 文件 + ServerName + DocumentRoot
如果你需要:
可以直接告诉我你的具体场景,我可以给你定制配置。