在 Ubuntu 上配置 Apache2 时,有几个常见且容易踩坑的点。下面按安装 → 配置 → 安全 → 排错来总结,都是实战经验。
sudo apt update
sudo apt install apache2
sudo systemctl start apache2
sudo systemctl enable apache2
sudo systemctl status apache2
✅ 看到
active (running)才正常
sudo ufw allow 'Apache Full'
sudo ufw reload
确认:
sudo ufw status
常见端口:
/var/www/html
⚠️ 不要直接 chmod 777
推荐做法:
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
✅
www-data是 Apache 的运行用户
sudo cp /etc/apache2/sites-available/000-default.conf \
/etc/apache2/sites-available/example.conf
编辑:
sudo nano /etc/apache2/sites-available/example.conf
基本模板:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example
<Directory /var/www/example>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
sudo a2ensite example.conf
sudo systemctl reload apache2
sudo a2dissite 000-default.conf
sudo a2enmod rewrite
sudo a2enmod ssl
sudo a2enmod headers
然后:
sudo systemctl restart apache2
<Directory /var/www/html>
AllowOverride All
</Directory>
sudo a2enmod rewrite
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
✅ 自动配置 HTTPS + 自动续期
检查续期:
sudo certbot renew --dry-run
/var/log/apache2/error.log
/var/log/apache2/access.log
sudo tail -f /var/log/apache2/error.log
| 问题 | 原因 |
|---|---|
| 403 Forbidden | 目录权限 / 没有 index 文件 |
| 404 | DocumentRoot 写错 |
| .htaccess 无效 | AllowOverride 没开 |
| 端口占用 | nginx / 其他服务占 80 |
| 配置不生效 | 忘了 reload / restart |
✅ 关闭目录浏览:
Options -Indexes
✅ 隐藏 Apache 版本:
ServerTokens Prod
ServerSignature Off
✅ 限制访问:
<Directory /var/www/html/admin>
Require ip 1.2.3.4
</Directory>
Ubuntu + Apache2 配置记住这 5 点:
如果你愿意,可以告诉我:
我可以给你一份完全贴合你场景的 Apache2 配置示例。