DevOps约 3 分钟阅读

用 Nginx + Let's Encrypt 部署一个 HTTPS 静态网站

本站(goldpoints.cn)就是一个纯静态网站,跑在一台普通的云服务器上。本文把完整的部署步骤整理出来,照着做大约 15 分钟即可上线。

#准备工作

  • 一台 Linux 服务器(本文以 Ubuntu 24.04 为例)
  • 一个已解析到服务器 IP 的域名(A 记录)
  • 国内服务器需完成 ICP 备案,否则 80/443 端口会被拦截

#安装 Nginx

bash
apt update
apt install -y nginx
systemctl enable --now nginx

浏览器访问服务器 IP,看到 “Welcome to nginx!” 说明安装成功。

#上传网站文件

约定网站根目录为 /var/www/example.com:

bash
mkdir -p /var/www/example.com
# 在本地执行,把构建产物同步到服务器
rsync -avz --delete dist/ root@your-server:/var/www/example.com/

#编写站点配置

新建 /etc/nginx/sites-available/example.com:

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com;
    index index.html;

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

    # 带版本号的静态资源可以长期缓存
    location /assets/ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    error_page 404 /404.html;

    gzip on;
    gzip_types text/css application/javascript application/json image/svg+xml application/xml;
}

启用并检查配置:

bash
ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx

一定要先 nginx -t 再 reload。配置有语法错误时,reload 会失败,但不会影响正在运行的旧配置。

#申请 HTTPS 证书

bash
apt install -y certbot python3-certbot-nginx
certbot --nginx -d example.com -d www.example.com --redirect

--redirect 会自动添加 HTTP → HTTPS 的 301 跳转。certbot 安装时会注册一个 systemd timer 自动续期,可以用下面的命令验证:

bash
systemctl list-timers | grep certbot
certbot renew --dry-run

#小结

步骤 命令
安装 apt install nginx
校验配置 nginx -t
平滑重载 systemctl reload nginx
证书 certbot --nginx -d 域名

静态网站几乎没有攻击面,也几乎不占服务器资源,是个人技术博客的最佳选择。