为服务器开启https访问

要开启 HTTPS 访问,你需要为你的域名配置 SSL 证书,并修改 Nginx 配置以支持 HTTPS。以下是具体步骤:


1. 获取 SSL 证书

推荐使用 Let’s Encrypt 免费 SSL 证书。你可以使用 certbot 工具来获取证书。

在主机A上安装 Certbot

sudo apt update
sudo apt install certbot

获取 SSL 证书

运行以下命令获取证书(确保域名已解析到主机A的IP地址):

sudo certbot certonly --standalone -d your-domain.com
  • your-domain.com 替换为你的实际域名。
  • 证书会保存在 /etc/letsencrypt/live/your-domain.com/ 目录下。

2. 修改 Nginx 配置文件

更新主机A上的 Nginx 配置文件,使其支持 HTTPS。

编辑之前创建的 reverse-proxy.conf 文件:

nano ~/nginx-proxy/conf.d/reverse-proxy.conf

修改为以下内容:

server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$host$request_uri; # 将所有 HTTP 请求重定向到 HTTPS
}

server {
    listen 443 ssl;
    server_name your-domain.com;

    ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        proxy_pass http://<服务器B的IP地址>:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

3. 修改 Docker Compose 文件

为了让 Nginx 容器能够访问主机上的 SSL 证书文件,需要将证书目录挂载到容器中。

编辑 docker-compose.yml 文件:

nano ~/nginx-proxy/docker-compose.yml

修改为以下内容:

version: '3'
services:
  nginx:
    image: nginx:latest
    container_name: nginx-proxy
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./conf.d:/etc/nginx/conf.d
      - /etc/letsencrypt:/etc/letsencrypt
    restart: always

4. 重启 Nginx 容器

更新配置后,重启 Nginx 容器以应用更改:

cd ~/nginx-proxy
docker-compose down
docker-compose up -d

5. 测试 HTTPS 访问

现在,你可以通过以下方式测试 HTTPS 是否正常工作:

  1. 访问 https://your-domain.com,确保能够正常加载服务器B的内容。
  2. 检查浏览器地址栏,确认显示为安全的 HTTPS 连接(小锁图标)。

6. 自动更新 SSL 证书(可选)

Let’s Encrypt 证书有效期为 90 天,需要定期更新。可以通过以下步骤设置自动更新。

手动测试更新

sudo certbot renew --dry-run

设置定时任务

编辑 crontab:

sudo crontab -e

添加以下内容,每天凌晨 2 点检查并更新证书:

0 2 * * * certbot renew --quiet --post-hook "docker restart nginx-proxy"

7. 防火墙配置

确保主机A的防火墙允许 HTTPS 流量(443 端口):

sudo ufw allow 443

总结

通过以上步骤,你已经成功配置了 HTTPS 访问:

  1. 使用 Let’s Encrypt 获取 SSL 证书。
  2. 修改 Nginx 配置以支持 HTTPS。
  3. 挂载 SSL 证书到 Docker 容器。
  4. 重启 Nginx 并测试 HTTPS 访问。

如果遇到问题,可以检查 Nginx 日志(docker logs nginx-proxy)或 Certbot 日志(/var/log/letsencrypt/)来排查问题。

This entry was posted in 网络相关 and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *