Nginx 网站首次上线步骤:HTTP 先行、签证书、切 HTTPS
新站上线的正确顺序:DNS 和端口、确认 Nginx 版本、阶段一纯 HTTP 配置、certbot certonly --webroot 签证书、阶段二 HTTPS、续期检查、分文件打包回滚和 Cloudflare 注意事项。
域名解析和端口
把域名(和 www)的 A / AAAA 记录指向服务器,确认 80 和 443 端口在系统防火墙和云厂商安全组里都放行。证书签发走 80 端口,80 不通就签不下来。
dig +short example.com A dig +short www.example.com A sudo ufw allow 'Nginx Full' # Ubuntu/Debian ufw sudo firewall-cmd --permanent --add-service={http,https} && sudo firewall-cmd --reload # RHEL 系安装 Nginx,记下版本
nginx.org 官方源版本较新;发行版自带的版本可能较旧(Debian 12 是 1.22,Ubuntu 24.04 是 1.24),低于 1.25.1 时在生成器里把「Nginx 版本」选成 < 1.25.1,否则 http2 on 会报 unknown directive。
curl -fsSL nginx.cc/install | sudo bash # nginx.org 官方源,支持 --dry-run nginx -v
弄清配置放在哪
nginx.org 版和 Docker 镜像读取 /etc/nginx/conf.d/*.conf;Debian/Ubuntu 的 apt 版同时读取 conf.d 和 sites-enabled。本站生成的文件都放 conf.d。apt 版自带的 sites-enabled/default 占用了 80 端口的 default_server,用「HTTPS 跳转」兜底配置前要删掉它。
sudo nginx -T 2>/dev/null | grep -E '^# configuration file' sudo rm -f /etc/nginx/sites-enabled/default # 仅 Debian/Ubuntu apt 版
阶段一:先上线纯 HTTP 配置
证书还不存在时,带 ssl_certificate 的配置会让 nginx -t 失败。生成器在 HTTPS 场景下会同时给出「阶段一配置」:只有 80 端口,带 /.well-known/acme-challenge/ 的 webroot。先用它上线,再用一个测试文件确认外网能访问到。
sudo mkdir -p /var/www/_letsencrypt/.well-known/acme-challenge echo ok | sudo tee /var/www/_letsencrypt/.well-known/acme-challenge/ping sudo nginx -t && sudo systemctl reload nginx curl -s http://example.com/.well-known/acme-challenge/ping # 应输出 ok
签发证书
推荐 certbot certonly --webroot:只签证书,不改 nginx 配置,以后续期也不会动你的文件。--cert-name 固定证书目录名,和生成器里的路径对应。也可以用 certonly --nginx。通配符证书只能用 DNS 验证。
sudo apt install certbot # 或 sudo snap install --classic certbot sudo certbot certonly --webroot -w /var/www/_letsencrypt \ -d example.com -d www.example.com --cert-name example.com \ --email you@example.com --agree-tos --no-eff-email \ --deploy-hook "systemctl reload nginx"
不建议让 certbot --nginx(不带 certonly)直接改写生成的配置,它会插入自己的 ssl 参数,和 TLS 档位冲突。
阶段二:换成完整 HTTPS 配置
用生成器的「完整配置」覆盖同一个文件,检查语法后重载。80 端口的 server 仍保留 acme-challenge,续期不受影响。
sudo nginx -t && sudo systemctl reload nginx curl -sI https://example.com | head -20 curl -sI http://www.example.com | grep -i location
确认自动续期
certbot 安装时会带 systemd timer 或 cron。--dry-run 走一遍完整流程但不替换证书。
sudo certbot renew --dry-run systemctl list-timers | grep -i certbot
分文件打包的安装和回滚
分文件输出会把共用片段放到 /etc/nginx/nginxcc/,站点文件放 conf.d。解包前整目录备份,nginx -t 不通过就直接还原。
sudo cp -a /etc/nginx /etc/nginx.bak.$(date +%Y%m%d-%H%M%S) curl -fsSL 'https://nginx.cc/api/gen/bundle.tar.gz?…' | sudo tar -xzf - -C /etc/nginx sudo nginx -t && sudo systemctl reload nginx # 回滚:sudo rm -rf /etc/nginx && sudo mv /etc/nginx.bak.<时间> /etc/nginx
站点在 Cloudflare 后面
SSL/TLS 模式用 Full (strict),不要用 Flexible,否则源站的 HTTP→HTTPS 跳转会造成重定向循环。勾选生成器里的「站点在 Cloudflare 后面」,日志和限流才能拿到访客真实 IP。