在 Ubuntu 上配置 Apache2,一般分为 安装、常用配置、虚拟主机、权限与安全 几个部分。下面给你一套实用且偏生产环境的配置说明(基于 Ubuntu 20.04 / 22.04 / 24.04,差异不大)。
sudo apt update
sudo apt install apache2 -y
安装完成后,Apache 会自动启动。
查看状态:
sudo systemctl status apache2
常用命令:
sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl enable apache2 # 开机自启
Ubuntu 对 Apache 做了 Debian 风格的管理,和源码安装不同:
/etc/apache2/
├── apache2.conf # 主配置文件(不要频繁改)
├── ports.conf # 监听端口
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 已启用站点(软链接)
├── mods-available/ # 可用模块
├── mods-enabled/ # 已启用模块
├── conf-available/ # 额外配置
└── conf-enabled/
✅ 不要直接改 sites-enabled 里的文件
✅ 正确做法:改 sites-available,然后启用
浏览器访问:
http://服务器IP
看到 Apache2 Ubuntu Default Page 即成功。
如果使用 ufw:
sudo ufw allow OpenSSH
sudo ufw allow 'Apache Full'
sudo ufw enable
查看:
sudo ufw status
example.comsudo mkdir -p /var/www/example.com/public_html
sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www
创建测试页面:
echo "<h1>Example.com works</h1>" | sudo tee /var/www/example.com/public_html/index.html
sudo nano /etc/apache2/sites-available/example.com.conf
内容示例(推荐):
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
<Directory /var/www/example.com/public_html>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>
sudo a2ensite example.com.conf
sudo a2dissite 000-default.conf # 可选:禁用默认站点
sudo systemctl reload apache2
sudo a2enmod rewrite
sudo systemctl restart apache2
sudo a2enmod ssl
sudo systemctl restart apache2
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d example.com -d www.example.com
自动:
查看续期状态:
sudo certbot renew --dry-run
sudo apt install php libapache2-mod-php php-mysql -y
sudo systemctl restart apache2
测试:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
访问:
http://IP/info.php
✅ 网站目录属主:
sudo chown -R www-data:www-data /var/www
✅ 禁止目录浏览:
Options -Indexes
✅ 禁用服务器信息泄漏:
ServerTokens Prod
ServerSignature Off
✅ 不要让 Apache 以 root 运行(Ubuntu 默认安全)
查看错误原因:
sudo journalctl -xe
sudo tail -n 50 /var/log/apache2/error.log
测试配置文件:
sudo apache2ctl configtest
apt install apache2
ufw allow 'Apache Full'
mkdir -p /var/www/xxx/public_html
a2ensite xxx.conf
a2enmod rewrite ssl
certbot --apache
如果你愿意,可以告诉我:
我可以给你 一对一定制 Apache 配置方案。