下面给你一份在 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 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 mkdir -p /var/www/example.com/public_html
创建测试页面:
echo "<h1>Example.com</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 webmaster@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 a2enmod rewrite
sudo systemctl restart apache2
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d example.com -d www.example.com
证书会自动续期。
Options -Indexes
DirectoryIndex index.php index.html
sudo apt install php libapache2-mod-php
sudo systemctl restart apache2
tail -f /var/log/apache2/error.log
sudo apache2ctl configtest
sudo netstat -tlnp | grep 80
sudo nano /etc/apache2/sites-available/local.conf
<VirtualHost *:80>
ServerName local.test
DocumentRoot /home/user/project
<Directory /home/user/project>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
sudo a2ensite local.conf
sudo systemctl restart apache2
然后在 /etc/hosts 添加:
127.0.0.1 local.test
如果你愿意,可以告诉我:
我可以给你一份完全定制化的 Apache2 配置方案。