AWS 服务器配置 Nginx + HTTPS(Let's Encrypt)

HTTP/TCPLiunxTechnology

AWS 服务器配置 Nginx + HTTPS(Let's Encrypt)


✅ 你需要准备:

  1. 已成功解析的域名(如 yourdomain.com 指向了 AWS 公网 IP)
  2. Ubuntu 系统(你的是 ✅)
  3. 已安装 Nginx(没有可先运行:sudo apt install nginx -y

✅ 第一步:开放防火墙与 AWS 安全组

确保开放了 80 和 443 端口

1️⃣ AWS 控制台 → EC2 → 安全组设置:

  • 添加入站规则:
    • 类型:HTTP(端口 80)→ 允许所有
    • 类型:HTTPS(端口 443)→ 允许所有

2️⃣ 服务器内防火墙(如果你启用了 ufw):

bash
sudo ufw allow 'Nginx Full'

✅ 第二步:安装 Certbot + Nginx 插件(自动申请 HTTPS 证书)

bash
sudo apt update
sudo apt install certbot python3-certbot-nginx -y

✅ 第三步:配置 Nginx(添加你的域名转发规则)

假设你的服务监听在 http://localhost:7788

创建一个配置文件:

bash
sudo nano /etc/nginx/sites-available/blog

粘贴以下内容(替换域名):

nginx
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    location / {
        proxy_pass http://localhost:7788;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

保存退出后启用配置:

bash
sudo ln -s /etc/nginx/sites-available/blog /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

✅ 第四步:申请 HTTPS 证书并自动配置 Nginx

运行命令:

bash
sudo certbot --nginx

根据提示:

  • 选择你的域名(如 yourdomain.com
  • 选择 2:自动将 HTTP 重定向到 HTTPS

如果成功,会看到:

Congratulations! Your certificate and chain have been saved at:
...

✅ 第五步:验证 HTTPS 是否生效

打开浏览器访问:

https://yourdomain.com

应可访问你的博客 API(或页面),并看到小锁图标 🔒。


✅ 附加:设置自动续期(Certbot 会自动添加定时任务)

可以用下面命令测试续期是否生效:

bash
sudo certbot renew --dry-run