Apache:安装与虚拟主机
在 VPS 上安装 Apache、配置虚拟主机和模块,以及排查与 Nginx 在 80 端口上的常见冲突。
更新于 2026年8月23日
当您需要 .htaccess、旧版 CMS,或应用程序开发者提供的现成指南时,就选择 Apache。它比 Nginx 更占内存,但在 VDS-1 上只跑一个小网站,您不会察觉。
安装
apt update && apt install -y apache2 # Debian, Ubuntu
dnf install -y httpd && systemctl enable --now httpd # AlmaLinux, CentOS Stream
服务名称不同:Debian 和 Ubuntu 上是 apache2,RHEL 系列中是 httpd。配置目录也不一样——/etc/apache2 和 /etc/httpd。
检查:
systemctl status apache2
curl -I http://127.0.0.1
虚拟主机
文件 /etc/apache2/sites-available/example.ru.conf:
<VirtualHost *:80>
ServerName example.ru
ServerAlias www.example.ru
DocumentRoot /var/www/example.ru
<Directory /var/www/example.ru>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example.ru-error.log
CustomLog ${APACHE_LOG_DIR}/example.ru-access.log combined
</VirtualHost>
启用并检查:
a2ensite example.ru
a2dissite 000-default
apachectl configtest && systemctl reload apache2
只有当您确实使用 .htaccess 时才需要 AllowOverride All。如果不用,就设为 None:这样 Apache 就不会在每次请求时到每个目录中查找这些文件。
模块
a2enmod rewrite headers ssl
systemctl restart apache2
要列出已启用的模块——apache2ctl -M。不要启用所有模块:每个模块都会被加载到每个工作进程中。
对于 PHP,请使用 PHP-FPM,而不是过时的 mod_php:PHP-FPM。
Apache 与 Nginx 共存
两个服务器默认都监听 80 端口,因此第二个根本无法启动,并会抛出 Address already in use。您有两个选择:
- 只保留一个服务器;
- 把 Nginx 放在前面,将 Apache 改为
Listen 127.0.0.1:8080,然后反向代理到它——参见反向代理。
查看端口被谁占用:
ss -tulpn | grep :80
常见错误
| 现象 | 原因 |
|---|---|
AH00558: Could not reliably determine ... server's fully qualified domain name | 未设置 ServerName——这只是警告,但还是设置一下为好 |
.htaccess 不生效 | Directory 块中为 AllowOverride None |
| 修改后服务无法启动 | 语法错误——重载前务必运行 apachectl configtest |
| 访问目录返回 403 | 缺少 Require all granted,或 www-data 没有权限 |
日志:/var/log/apache2/(Debian、Ubuntu)或 /var/log/httpd/(AlmaLinux)。
每次修改前先复制配置:
cp file file.bak。在虚拟机上,回滚比努力回忆一小时前改了什么要容易得多。