在 Ubuntu 上安装与配置 Apache 的简明步骤
一 安装与启动
sudo apt update
sudo apt install apache2 -y
sudo systemctl status apache2
正常会看到 Active: active (running);如未运行可执行:sudo systemctl start apache2
sudo systemctl enable apache2
二 防火墙放行
sudo ufw allow 'Apache Full'
sudo ufw status
如仅放行 HTTP:sudo ufw allow 80/tcp
注意:云服务器还需在云平台安全组放行 80/443 端口。三 部署网站与虚拟主机
sudo mkdir -p /var/www/example.com/public_html
echo "<h1>Welcome to 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 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>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>
sudo a2ensite example.com.conf
sudo apachectl configtest # 语法检查
sudo systemctl reload apache2
四 启用 HTTPS 与自动续期
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d example.com -d www.example.com
五 常用管理与卸载
sudo systemctl restart apache2 # 重启
sudo systemctl reload apache2 # 重新加载配置
sudo apachectl configtest # 语法检查
sudo a2enmod deflate cache cache_disk # 启用压缩与缓存模块(按需)
sudo a2dissite example.com.conf && sudo systemctl reload apache2 # 禁用站点
sudo systemctl stop apache2
sudo apt remove apache2 -y
sudo apt purge apache2 -y
sudo apt autoremove -y