用 Apache2 搭建网站的标准流程
一 准备与安装
sudo apt update
sudo apt install apache2 -y
sudo systemctl start apache2
sudo systemctl enable apache2
sudo yum install httpd -y # CentOS 7
# 或
sudo dnf install httpd -y # CentOS 8+/RHEL 8+
sudo systemctl start httpd
sudo systemctl enable httpd
二 部署静态网站
# Ubuntu/Debian 常用目录
sudo mkdir -p /var/www/mywebsite
echo "<h1>Hello, Apache2</h1>" | sudo tee /var/www/mywebsite/index.html
# CentOS/RHEL 建议将属主设为 Apache 运行用户
sudo chown -R apache:apache /var/www/mywebsite
sudo chmod -R 755 /var/www/mywebsite
三 配置虚拟主机与目录权限
sudo nano /etc/apache2/sites-available/mywebsite.conf
示例内容(将 mywebsite.com 替换为你的域名):<VirtualHost *:80>
ServerAdmin webmaster@mywebsite.com
ServerName mywebsite.com
ServerAlias www.mywebsite.com
DocumentRoot /var/www/mywebsite
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory /var/www/mywebsite>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
sudo a2ensite mywebsite.conf
sudo a2dissite 000-default.conf # 可选
sudo systemctl reload apache2
sudo nano /etc/httpd/conf.d/mywebsite.conf
示例内容:<VirtualHost *:80>
ServerName mywebsite.com
DocumentRoot /var/www/mywebsite
<Directory /var/www/mywebsite>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
sudo systemctl reload httpd
四 防火墙与端口放行
sudo ufw allow 'Apache Full' # 同时放行 80/443
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
五 启用 HTTPS 与常见问题排查
# Ubuntu/Debian
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d mywebsite.com -d www.mywebsite.com
# CentOS/RHEL(如系统默认 python 为 Python 2,使用 python2-certbot-apache)
sudo yum install certbot python2-certbot-apache -y # 或 dnf
sudo certbot --apache -d mywebsite.com -d www.mywebsite.com
按提示选择是否重定向 HTTP→HTTPS,证书将自动续期。sudo systemctl status apache2(或 httpd)sudo tail -f /var/log/apache2/error.log(Ubuntu/Debian),或 /var/log/httpd/error_log(CentOS/RHEL)