Apache VirtualHost 配置核心是通过域名、IP或端口区分多站点,需启用主配置中的Include指令、设置正确目录权限、编写含ServerName/DocumentRoot/Directory权限的虚拟主机块,并启用配置后重启服务。
Apache 中 VirtualHost 的配置与管理,核心是让一台服务器响应多个域名(或 IP、端口),每个站点拥有独立的根目录、日志和权限控制。关键不在堆参数,而在结构清晰、权限到位、启用正确。
Apache 不会自动读取 VirtualHost 块,必须显式启用相关配置文件。常见操作包括:
/etc/apache2/apache2.conf 或 /etc/httpd/conf/httpd.conf)Include conf/extra/httpd-vhosts.conf 或 IncludeOptional sites-enabled/*.conf 的行,去掉前面的 # 取消注释Listen 80(HTTP)或 Listen 443(HTTPS)sudo apache2ctl -t(Debian/Ubuntu)或 sudo httpd -t(CentOS/RHEL)验证语法,输出 Syntax OK 才继续目录路径要明确,Apache 进程(通常是 www-data 或 apache 用户)必须能读取和进入目录,否则返回 403 错误。
sudo mkdir -p /var/www/site-a.com/public_html
echo "<h1>Site A</h1>" > /var/www/site-a.com/public_html/index.html
sudo chown -R $USER:www-data /var/www/site-a.com
sudo chmod -R 755 /var/www/site-a.com
这是最常用的方式,同一 IP 和端口靠请求头中的 Host 字段区分站点。配置需包含三部分:基本定义、目录权限、日志(可选但建议)。
/etc/apache2/sites-available/site-a.com.conf(Debian/Ubuntu)或 /etc/httpd/conf/extra/httpd-vhosts.conf(CentOS)中写入:ServerName site-a.com
ServerAlias www.site-a.com
DocumentRoot "/var/www/site-a.com/public_html"
<Directory "/var/www/site-a.com/public_html">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/site-a_error.log
CustomLog ${APACHE_LOG_DIR}/site-a_access.log combined
</VirtualHost>
ServerAlias 可写多个,用空格分隔;AllowOverride All 启用 .htaccess 支持;Require all granted 是 Apache 2.4+ 的必需权限指令写完不等于生效,还需启用并重启服务。
sudo a2ensite site-a.com.conf(自动创建符号链接到 sites-enabled)httpd-vhosts.conf 或单独文件后,确保它被主配置 Include 到即可sudo systemctl restart apache2(或 httpd)/etc/hosts 添加:127.0.0.1 site-a.com,然后浏览器访问 http://site-a.com