You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx+Django环境下HTTPS非www转www重定向问题求助

问题分析

你遇到的核心问题:

  • Nginx配置里的域名拼写错误(exmaple.com应为example.com),导致规则完全不匹配
  • 仅为www.example.com配置SSL证书,但443端口的server块同时绑定两个域名,访问https://example.com时证书不匹配,触发安全提示
  • 当前配置只处理了80端口的重定向,未覆盖443端口的不带www请求
解决方案

1. 修正域名拼写错误

把配置中所有的exmaple.com替换为example.com,这是配置生效的基础前提。

2. 更新SSL证书(关键)

你需要申请包含example.com和www.example.com双域名的SSL证书,执行以下命令:

certbot --nginx -d example.com -d www.example.com

Certbot会自动生成覆盖双域名的证书,并自动调整部分Nginx配置,确保证书同时适配两个域名。

3. 调整Nginx配置

替换为以下配置,确保所有HTTP/HTTPS请求都重定向到https://www.example.com,且证书匹配:

# 处理所有80端口请求,统一重定向到HTTPS带www的域名
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://www.example.com$request_uri;
}

# 处理不带www的HTTPS请求,重定向到带www的HTTPS域名
server {
    listen 443 ssl;
    server_name example.com;

    # 使用覆盖双域名的证书文件
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    return 301 https://www.example.com$request_uri;
}

# 处理带www的HTTPS请求,正常代理到后端服务
server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location ~ ^/.well-known {
        root /home/xyz/xyz-dir;
        allow all;
    }

    location = /favicon.ico { 
        access_log off; 
        log_not_found off; 
    }

    location /static/ {
        root /home/xyz/xyz-dir;
    }

    location /media/ {
        root /home/xyz/xyz-dir;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

4. 验证配置并重启Nginx

执行命令检查配置合法性:

nginx -t

如果输出test is successful,重启Nginx使配置生效:

systemctl restart nginx

内容的提问来源于stack exchange,提问作者Niiteesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 23:00:26