在 Ubuntu 上配置 Apache(通常是 Apache2) 时,有几个常见但容易踩坑的点,下面按「安装 → 配置 → 权限 → 安全 → 排错」给你梳理一下。
sudo apt update
sudo apt install apache2
sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl enable apache2
sudo systemctl status apache2
Ubuntu 的 Apache 结构和 CentOS 不太一样:
/etc/apache2/
├── apache2.conf # 主配置(不要直接乱改)
├── ports.conf # 端口配置
├── sites-available/ # 可用站点(配置在这里)
├── sites-enabled/ # 启用站点(软链接)
├── mods-available/
├── mods-enabled/
└── conf-available/
✅ 正确做法:
sites-available/sudo a2ensite your-site.conf
sudo a2dissite 000-default.conf
sudo systemsctl reload apache2
/var/www/html
www-data
设置权限示例:
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
⚠️ 不要把目录设成 777
示例 /etc/apache2/sites-available/example.conf:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example
<Directory /var/www/example>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example_error.log
CustomLog ${APACHE_LOG_DIR}/example_access.log combined
</VirtualHost>
启用:
sudo a2ensite example.conf
sudo systemctl reload apache2
如果你用 WordPress、Laravel 等:
sudo a2enmod rewrite
并确保:
AllowOverride All
否则 .htaccess 不生效。
Ubuntu 常用 UFW:
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
自动配置 80 → 443。
❌ 改了配置不生效
✅ 记得 reload 或 restart
❌ 403 Forbidden
✅ 检查:
❌ 站点不显示
✅ 检查:
sudo tail -f /var/log/apache2/error.log
sudo tail -f /var/log/apache2/access.log
如果你愿意,可以告诉我:
我可以直接给你一份可复制的配置模板。