下面给你一份在 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 enable apache2 # 开机自启
sudo ufw allow 'Apache Full'
查看:
sudo ufw status
浏览器访问:
http://服务器IP
看到 Apache2 Ubuntu Default Page 即成功。
| 路径 | 作用 |
|---|---|
/var/www/html |
默认网站目录 |
/etc/apache2/apache2.conf |
主配置文件 |
/etc/apache2/sites-available/ |
虚拟主机配置(可用) |
/etc/apache2/sites-enabled/ |
已启用的虚拟主机 |
/etc/apache2/mods-available/ |
可用模块 |
/etc/apache2/mods-enabled/ |
已启用模块 |
/var/log/apache2/ |
日志目录 |
sudo nano /etc/apache2/sites-available/000-default.conf
修改:
DocumentRoot /var/www/myweb
sudo mkdir -p /var/www/myweb
sudo chown -R www-data:www-data /var/www/myweb
sudo chmod -R 755 /var/www/myweb
sudo systemctl restart apache2
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
确保目录中:
AllowOverride All
sudo apt install php libapache2-mod-php
sudo systemctl restart apache2
测试:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
访问:
http://IP/info.php
index.html / index.php<Directory> 未允许访问sudo apache2ctl configtest
sudo netstat -tlnp | grep :80
使用 Let’s Encrypt:
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
如果你愿意,我可以帮你:
告诉我你的 Ubuntu 版本 和 具体需求 即可。