下面给你一个在 Ubuntu 上配置 Apache2 的完整入门指南,从安装到常见配置(虚拟主机、端口、HTTPS、权限等),适合大多数使用场景。
sudo apt update
sudo apt install apache2
安装完成后,Apache 会自动启动。
查看状态:
sudo systemctl status apache2
常用命令:
sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl reload apache2
如果启用了 UFW,需要放行 HTTP / HTTPS:
sudo ufw allow 80
sudo ufw allow 443
sudo ufw reload
验证:
sudo ufw status
浏览器访问:
http://服务器IP
看到 Apache2 Ubuntu Default Page 说明成功。
默认网站目录:
/var/www/html
假设你的网站目录是 /var/www/html:
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
www-data是 Apache 运行的用户
sudo mkdir -p /var/www/example.com
sudo chown -R www-data:www-data /var/www/example.com
创建测试页面:
echo "Hello Apache" | sudo tee /var/www/example.com/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
<Directory /var/www/example.com>
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 systemctl reload apache2
禁用默认站点(可选):
sudo a2dissite 000-default.conf
很多程序(WordPress、Laravel)需要:
sudo a2enmod rewrite
sudo systemctl restart apache2
确保目录中:
AllowOverride All
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d example.com -d www.example.com
sudo certbot renew --dry-run
证书有效期 90 天,自动续期已配置
编辑:
sudo nano /etc/apache2/ports.conf
例如:
Listen 8080
修改虚拟主机:
<VirtualHost *:8080>
sudo systemctl restart apache2
| 功能 | 路径 |
|---|---|
| 主配置 | /etc/apache2/apache2.conf |
| 虚拟主机 | /etc/apache2/sites-available/ |
| 已启用站点 | /etc/apache2/sites-enabled/ |
| 模块配置 | /etc/apache2/mods-available/ |
| 端口配置 | /etc/apache2/ports.conf |
| 日志 | /var/log/apache2/ |
| 网站目录 | /var/www/ |
Directory 未配置 Require all grantedDocumentRoot 路径错误sudo apache2ctl configtest
sudo journalctl -xe
如果你愿意,可以告诉我:
我可以给你更精确的配置方案。