下面给你一个快速配置 Ubuntu Apache2 的实用步骤,适合刚装完系统或需要快速搭建 Web 服务的情况(以 Ubuntu 20.04 / 22.04 为例)。
sudo apt update
sudo apt install apache2 -y
安装完成后,Apache 会自动启动。
sudo systemctl status apache2
正常应看到 active (running)。
常用命令:
sudo systemctl start apache2 # 启动
sudo systemctl stop apache2 # 停止
sudo systemctl restart apache2 # 重启
sudo systemctl enable apache2 # 开机自启
sudo ufw allow 80 # HTTP
sudo ufw allow 443 # HTTPS
sudo ufw reload
验证:
sudo ufw status
浏览器访问:
http://服务器IP
看到 Apache2 Ubuntu Default Page 即成功。
sudo mkdir -p /var/www/example.com/public_html
echo "<h1>Hello Apache2</h1>" | sudo tee /var/www/example.com/public_html/index.html
sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www
sudo nano /etc/apache2/sites-available/example.com.conf
内容示例:
<VirtualHost *:80>
ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
<Directory /var/www/example.com/public_html>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/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
| 作用 | 路径 |
|---|---|
| 主配置 | /etc/apache2/apache2.conf |
| 虚拟主机 | /etc/apache2/sites-available/ |
| 启用站点 | /etc/apache2/sites-enabled/ |
| 网站根目录 | /var/www/ |
| 日志 | /var/log/apache2/ |
✅ 403 Forbidden
→ 目录权限或 <Directory> 配置错误
✅ 端口被占用
sudo netstat -tlnp | grep 80
✅ 修改配置不生效
sudo apache2ctl configtest
sudo systemctl reload apache2
如果你需要:
可以直接告诉我你的使用场景,我可以给你更精简或定制化的配置方案。