🧱 前提条件

  • 一台已安装 Rocky Linux 8/9 的服务器
  • 拥有 root 权限 或配置了 sudo 的普通用户
  • 一个已注册的 域名(例如:example.com
  • 域名的 DNS 已正确解析到你的服务器公网 IP(A 记录)

第一步:更新系统

sudo dnf update -y

第二步:安装 Nginx

Rocky Linux 默认仓库中包含 Nginx:

sudo dnf install nginx -y

启动并设置开机自启:

sudo systemctl enable --now nginx

验证 Nginx 是否运行:

sudo systemctl status nginx

此时访问 http://你的服务器IP 应看到 Nginx 默认欢迎页。


第三步:准备静态 HTML 站点

1. 创建站点目录(以 example.com 为例)

sudo mkdir -p /var/www/example.com/html

2. 设置权限(可选,但推荐)

sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www

3. 创建一个简单的 HTML 文件

cat <<EOF | sudo tee /var/www/example.com/html/index.html
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to example.com!</title>
</head>
<body>
    <h1>Success! Your static site is working.</h1>
</body>
</html>
EOF

第四步:配置 Nginx 虚拟主机(绑定域名)

1. 创建 Nginx 配置文件

sudo tee /etc/nginx/conf.d/example.com.conf <<EOF
server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/example.com/html;
    index index.html;

    location / {
        try_files \$uri \$uri/ =404;
    }
}
EOF

⚠️ 将 example.com 替换为你自己的域名。

2. 测试 Nginx 配置是否正确

sudo nginx -t

应看到 syntax is oktest is successful

3. 重载 Nginx

sudo systemctl reload nginx

此时通过浏览器访问 http://example.com 应显示你创建的 HTML 页面。


第五步:申请并安装 HTTPS 证书(使用 Certbot + Let's Encrypt)

1. 安装 EPEL 仓库和 snapd(Certbot 推荐方式)

sudo dnf install epel-release -y
sudo dnf install snapd -y
sudo systemctl enable --now snapd.socket
sudo ln -s /var/lib/snapd/snap /snap  # 启用经典 snap 支持

2. 安装 Certbot

sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

3. 获取并安装 SSL 证书(自动修改 Nginx 配置)

sudo certbot --nginx -d example.com -d www.example.com

按提示输入邮箱、同意条款,并选择是否将 HTTP 重定向到 HTTPS(建议选 )。

Certbot 会自动:

  • 申请证书
  • 修改 /etc/nginx/conf.d/example.com.conf
  • 添加 HTTPS 监听(443 端口)
  • 配置自动跳转 HTTPS

4. 验证 HTTPS 是否生效

访问 https://example.com,应看到绿色锁图标且页面正常加载。


第六步:设置证书自动续期(Let's Encrypt 证书 90 天有效)

Certbot 已自动配置 systemd 定时任务(通过 snap 安装时默认启用),但你可以手动测试:

sudo certbot renew --dry-run

如果无报错,说明自动续期已配置成功。

💡 提示:可通过 systemctl list-timers | grep certbot 查看定时任务。


✅ 完成!

你现在拥有:

  • 一个通过 Nginx 托管的静态 HTML 网站
  • 绑定自定义域名
  • 自动 HTTPS 加密(由 Let's Encrypt 提供)
  • 证书自动续期

🔒 可选安全建议

  • 配置防火墙(firewalld)仅开放 80/443 端口:
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
  • 定期更新系统:sudo dnf upgrade -y

如有问题,可检查日志:

  • Nginx 错误日志:/var/log/nginx/error.log
  • Certbot 日志:/var/log/letsencrypt/

祝你部署顺利!🌐