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

AWS EC2 Nginx配置下www前缀域名访问API返回405错误求助

问题排查与解决方案

核心问题定位

你当前的配置存在两个核心异常点:

  • www.example.com.au的HTTPS服务配置监听的是8443端口,但常规HTTPS请求默认走443端口,你没有配置监听443端口的server块处理www.example.com.au的HTTPS请求
  • 后端API服务大概率仅识别example.com.au的Host头,www.example.com.au的Host头请求到后端后被拦截返回405状态码

修复步骤

  1. 调整Nginx配置,补全443端口监听规则,适配双域名的API请求逻辑:
http {

  server {
    listen 80;
    server_name example.com.au www.example.com.au;

    location / {
      return 301 https://$host$request_uri;
    }
  }

  # 处理不带www的HTTPS请求
  server {
    listen 443 ssl;
    server_name example.com.au;
    ssl_certificate /etc/nginx/certs/example.com.cert;
    ssl_certificate_key /etc/nginx/certs/example.com.key;

    location /api {
      proxy_pass https://example_api_service:1001;
      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;
    }

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

  # 处理带www的HTTPS请求
  server {
    listen 443 ssl;
    server_name  www.example.com.au;
    ssl_certificate /etc/nginx/certs/example.com.cert;
    ssl_certificate_key /etc/nginx/certs/example.com.key;

    location /api {
      proxy_pass https://example_api_service:1001;
      # 适配后端API的Host校验规则,统一传不带www的Host
      proxy_set_header Host example.com.au;
      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;
    }
  }
}
  1. 调整AWS安全组规则,放行443端口的入站HTTPS流量
  2. 配置修改完成后执行nginx -t校验语法合法性,确认无误后执行nginx -s reload重载配置即可生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:30:01