在 Ubuntu 上配置 Apache2 的一般步骤如下(从安装到常见配置),适合新手到日常使用。
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 # 重新加载配置
sudo ufw allow 'Apache Full'
查看:
sudo ufw status
浏览器访问:
http://服务器IP
看到 Apache2 Ubuntu Default Page 即成功。
/var/www/html
/etc/apache2/
重要目录:
/etc/apache2/sites-available # 可用站点配置
/etc/apache2/sites-enabled # 已启用站点(软链接)
/etc/apache2/mods-available # 可用模块
/etc/apache2/mods-enabled # 已启用模块
sudo mkdir -p /var/www/example.com
sudo chown -R $USER:$USER /var/www/example.com
echo "<h1>Hello Apache2</h1>" > /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}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
sudo a2ensite example.com.conf
sudo systemctl reload apache2
禁用默认站点(可选):
sudo a2dissite 000-default.conf
sudo a2enmod rewrite
sudo systemctl restart apache2
.htaccess 才能生效。
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
自动配置 HTTPS 并续期。
<Directory> 未配置 Require all grantedsudo apache2ctl configtest
查看错误:
sudo tail -f /var/log/apache2/error.log
sudo apt install apache2
sudo a2ensite xxx.conf
sudo a2enmod rewrite
sudo systemctl restart apache2
如果你有 具体需求(比如:多站点、PHP、反向代理、Laravel、WordPress、HTTPS、权限问题),可以直接告诉我,我可以给你针对性配置示例。