🔥为域名快速配置HTTPS,提升数据传输安全性🔥

59 阅读1分钟

一、目标实现

通过域名 https://test.domain.com 访问服务器上运行的 9090 端口服务

deepseek_mermaid_20250814_84f1e7.png

二、前期准备

  1. 服务器安全组配置

    • 在云平台安全组中开放 443 (HTTPS) 端口
  2. 域名解析设置

    • 添加二级域名解析记录:test.domain.com → 服务器公网 IP
  3. 环境准备

    # 安装 Nginx
    yum install nginx -y
    systemctl start nginx
    
    # 安装 Certbot(Let's Encrypt 客户端)
    yum install certbot python3-certbot-nginx -y
    

三、配置实施

  1. 获取 SSL 证书

    certbot --nginx -d test.domain.com
    
    • 自动完成证书申请和 Nginx 配置
    • 证书路径:/etc/letsencrypt/live/test.domain.com/
  2. Nginx 代理配置
    创建或修改配置文件 /etc/nginx/conf.d/test.conf

    server {
        listen 443 ssl;
        server_name test.domain.com;
    
        # SSL 证书配置
        ssl_certificate /etc/letsencrypt/live/test.domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/test.domain.com/privkey.pem;
    
        # 反向代理设置
        location / {
            proxy_pass http://localhost:9090;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    
        # 启用 HTTP/2 提升性能
        listen 443 ssl http2;
    }
    
  3. 配置生效

    nginx -t         # 测试配置语法
    systemctl reload nginx  # 重载配置
    

四、常用命令参考

功能命令
Nginx 启动systemctl start nginx
Nginx 停止systemctl stop nginx
配置检查nginx -t
服务重启systemctl restart nginx
证书续期certbot renew --quiet

五、补充说明

  1. 建议设置证书自动续期:

    # 添加到 crontab (每月1号凌晨3点执行)
    0 3 1 * * certbot renew --quiet
    
  2. 如需强制 HTTP 跳转 HTTPS,可添加:

    server {
        listen 80;
        server_name test.domain.com;
        return 301 https://$host$request_uri;
    }
    

现在您可以通过 https://test.domain.com 安全访问服务器上的 9090 端口服务了。