Ubuntu 上 Apache2 配置教程
一 安装与启动
sudo apt update && sudo apt install apache2 -ysudo systemctl start apache2 与 sudo systemctl enable apache2sudo systemctl status apache2(看到 Active: active (running) 即正常)sudo ufw allow 'Apache Full'(同时放行 80/443)二 目录结构与配置文件
sudo a2ensite yourdomain.confsudo a2dissite yourdomain.confsudo a2enmod module_name(如 rewrite、ssl)sudo apache2ctl configtestsudo systemctl reload apache2(或重启:sudo systemctl restart apache2)三 配置虚拟主机
sudo mkdir -p /var/www/example.comecho "<h1>Hello example.com</h1>" | sudo tee /var/www/example.com/index.htmlsudo chown -R www-data:www-data /var/www/example.com && sudo chmod -R 755 /var/www/example.comsudo 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
<Directory /var/www/example.com>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example_error.log
CustomLog ${APACHE_LOG_DIR}/example_access.log combined
</VirtualHost>
sudo a2ensite example.com.confsudo a2dissite 000-default.confsudo apache2ctl configtestsudo systemctl reload apache2四 启用 HTTPS 与自动续期
sudo apt install certbot python3-certbot-apache -ysudo certbot --apache -d example.com -d www.example.comsudo certbot renew --dry-run五 常见问题与排查
www-data:www-data 与 755)<Directory> 中有 Require all grantedsudo apache2ctl configtest 检查语法sudo systemctl reload apache2 重载配置sudo tail -f /var/log/apache2/error.logsudo tail -f /var/log/apache2/access.logsudo ss -tulpen | grep ':80\|:443'