下面给你一份在 Ubuntu 上配置 Apache2 的实用指南,从安装到常见配置,适合新手和日常使用。
sudo apt update
sudo apt install apache2 -y
安装完成后,Apache 会自动启动。
查看状态:
sudo systemctl status apache2
若未启动:
sudo systemctl start apache2
sudo systemctl enable apache2
sudo ufw allow 'Apache Full'
测试访问:
http://服务器IP
看到 Apache2 Ubuntu Default Page 即成功。
默认网站根目录:
/var/www/html
默认配置文件:
/etc/apache2/sites-available/000-default.conf
主配置文件:
/etc/apache2/apache2.conf
sudo mkdir -p /var/www/example.com/public_html
echo "<h1>Hello Apache2</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>
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
重启 Apache:
sudo systemctl reload apache2
sudo a2enmod rewrite
sudo systemctl restart apache2
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d example.com -d www.example.com
自动续期测试:
sudo certbot renew --dry-run
sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl reload apache2
sudo apache2ctl configtest
如果你有具体需求(比如 PHP、WordPress、反向代理、多站点、局域网访问),可以告诉我,我可以直接给你对应配置。