在 Ubuntu 上配置 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 的 Apache2 配置结构和 CentOS 不同:
/etc/apache2/
├── apache2.conf # 主配置文件(少改)
├── ports.conf # 端口配置
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 启用的站点(软链接)
├── mods-available/
├── mods-enabled/
└── conf-available/
sites-enabled 里的文件sudo nano /etc/apache2/sites-available/example.conf
sudo a2ensite example.conf
sudo systemctl reload apache2
禁用站点:
sudo a2dissite 000-default.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>
DocumentRoot 目录必须存在sudo chown -R www-data:www-data /var/www/example
sudo chmod -R 755 /var/www/example
ServerName 不配置会报警告sudo a2enmod rewrite
sudo a2dismod status
sudo systemctl restart apache2
常用模块:
rewrite(伪静态)sslheadersproxyproxy_fcgi(PHP-FPM)sudo apt install php libapache2-mod-php
sudo systemctl restart apache2
sudo apt install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.1-fpm
sudo systemctl restart apache2
sudo a2enmod ssl
sudo a2ensite default-ssl
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
sudo ufw allow 'Apache Full'
ServerTokens Prod
ServerSignature Off
Options -Indexes
sudo ufw enable
sudo ufw allow OpenSSH
sudo ufw allow 'Apache Full'
/var/log/apache2/access.log
/var/log/apache2/error.log
sudo apache2ctl configtest
sudo journalctl -u apache2
常见错误:
Address already in use → 端口冲突403 Forbidden → 权限 / AllowOverride404 → DocumentRoot 错误sites-available + a2ensitewww-datareload / restart如果你有 具体用途(如 PHP 网站、反向代理、Docker、Laravel、WordPress),我可以给你一份针对性配置示例。