返回笔记列表

把网页放到服务器上:域名 + HTTPS 完整流程

你有了一台云服务器和一个域名,怎么把它们连起来、加上 HTTPS、让全世界都能访问?这篇按顺序走完整个流程。

一、整体流程

买域名 → DNS 解析 → 装 Nginx → 配置站点 → 申请 HTTPS 证书 → 上线

二、域名 DNS 解析

A 记录(指向服务器 IP)

到域名管理后台(阿里云/腾讯云/Cloudflare),添加 A 记录:

  • 主机记录:@(主域名)和 www
  • 记录值:你的服务器公网 IP
  • TTL:600(10分钟)

验证解析生效

dig +short yourdomain.com
# 应返回你的服务器 IP

dig +short www.yourdomain.com
# 同上

国内备案

服务器在国内(阿里云/腾讯云等),域名必须先完成 ICP 备案才能解析到国内服务器。没备案的话 DNS 解析会被拦截。

💡 提示:备案周期通常 7-15 个工作日,买完域名就提交,别等要上线了才搞。

三、安装 Nginx

# Ubuntu/Debian
sudo apt update
sudo apt install nginx

# 验证
sudo systemctl status nginx
curl -I http://localhost

四、配置站点

sudo nano /etc/nginx/sites-available/yourdomain
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    root /var/www/yourdomain;
    index index.html;

    # 静态文件
    location / {
        try_files $uri $uri/ =404;
    }

    # 缓存静态资源
    location ~* \.(css|js|jpg|jpeg|png|webp|svg|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
# 启用站点
sudo ln -s /etc/nginx/sites-available/yourdomain /etc/nginx/sites-enabled/
sudo nginx -t          # 检查配置语法
sudo systemctl reload nginx

五、申请 HTTPS 证书(Let's Encrypt)

# 安装 certbot
sudo apt install python3-certbot-nginx

# 一键申请 + 配置
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

certbot 会自动:申请证书 → 配置 Nginx 443 端口 → 设置 HTTP 自动跳转 HTTPS。

自动续期

Let's Encrypt 证书 90 天过期,certbot 装完会自动加 systemd timer 续期。验证一下:

sudo systemctl list-timers | grep certbot
# 应看到 certbot.timer 定期运行

# 手动测试续期(不真的续)
sudo certbot renew --dry-run

六、验证上线

# 检查 HTTP → HTTPS 跳转
curl -I http://yourdomain.com
# 应返回 301 Location: https://yourdomain.com

# 检查 HTTPS
curl -I https://yourdomain.com
# 应返回 200

# 检查证书
echo | openssl s_client -connect yourdomain.com:443 -servername yourdomain.com 2>/dev/null | openssl x509 -noout -dates

七、常见问题

访问慢

检查服务器所在区域和用户距离。国内用户访问海外服务器会慢,考虑 CDN(Cloudflare 免费版够用)。

证书申请失败

90% 是 DNS 没生效或备案没过。先用 dig 确认解析,再确认备案状态。

Nginx 配置报错

每次改完配置都跑 sudo nginx -t,有错不会 reload 失败。常见错误:漏分号、少大括号。