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

Nginx配置api.example.com重定向至新域名遇404错误求助

问题分析与解决方案

你的核心问题是api.example.com的HTTPS请求未执行重定向,仍直接代理到localhost:5000;同时api.example2.com未配置对应服务路径,导致重定向后出现404。curl返回301是HTTP请求的正常响应,但HTTPS请求走的是第二个server块,未触发跳转逻辑。

步骤1:修正api.example.com的HTTPS配置

将443端口的server块改为重定向逻辑,确保HTTP、HTTPS请求都能跳转到api.example2.com:

server {
    listen 443 ssl;
    server_name api.example.com;
    ssl_certificate  /etc/nginx/ssl/example2.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example2.key;
    ssl_protocols TLSv1.2 TLSv1.3; # 仅保留安全协议版本
    ssl_ciphers HIGH:!aNULL:!MD5;

    return 301 https://api.example2.com$request_uri;
}

步骤2:配置api.example2.com的服务

在*.example2.com的Nginx配置中,新增专门的server块处理api.example2.com的请求,指向localhost:5000:

server {
    listen 443 ssl;
    server_name api.example2.com;
    ssl_certificate  /etc/nginx/ssl/example2.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example2.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade; # 适配WebSocket等动态场景
        proxy_set_header Host $host; # 确保后端服务识别api.example2.com域名
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# 新增HTTP到HTTPS的重定向(若未配置)
server {
    listen 80;
    listen [::]:80;
    server_name api.example2.com;
    return 301 https://$host$request_uri;
}

步骤3:验证配置并重启Nginx

  1. 检查Nginx配置语法正确性:
nginx -t
  1. 重启Nginx使配置生效:
systemctl restart nginx

关键注意事项

  • 确认example2.com.crt和example2.key为通配符证书,可覆盖api.example2.com
  • 若api.example2.com与其他example2.com站点共用server块,需确保location规则无冲突
  • 测试时用curl -I https://api.example.com验证HTTPS请求返回301,再访问https://api.example2.com确认服务正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:42:35