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状态码
修复步骤
- 调整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; } } }
- 调整AWS安全组规则,放行443端口的入站HTTPS流量
- 配置修改完成后执行
nginx -t校验语法合法性,确认无误后执行nginx -s reload重载配置即可生效
内容的提问来源于stack exchange,提问作者Madura Herath
相关产品推荐
相关产品推荐

