Nginx配置问题:无尾斜杠访问/api/some-folder无法返回index.json
Nginx alias路径无尾斜杠访问重定向端口错误的解决方法
问题场景
- Nginx Docker实例监听8080端口,配置中通过
alias将/api/some-folder映射到本地/some-folder目录(存放JSON文件) - 带尾斜杠访问
http://localhost:8080/api/some-folder/可正常返回index.json,子目录文件访问也正常 - 不带尾斜杠访问
http://localhost:8080/api/some-folder时,会被错误重定向到http://localhost/api/some-folder/,因80端口未提供服务导致无法访问
问题原因
当Nginx处理不带尾斜杠的目录请求时,默认会触发301重定向,但在alias配置场景下,尤其是Docker端口映射的环境中,Nginx生成重定向URL时未正确保留当前监听的端口(8080),直接使用了默认的80端口。
解决方案
方案1:统一location与alias的尾斜杠
将location和alias都加上尾斜杠,让Nginx正确识别目录请求并生成带端口的重定向URL:
events {} http { server { index index.json; location /api/some-folder/ { alias /some-folder/; default_type application/json; add_header Content-Type application/json; } } }
方案2:自定义rewrite规则强制保留端口
如果需要兼容带/不带尾斜杠的访问,添加rewrite规则手动指定重定向的完整URL(包含端口):
events {} http { server { index index.json; # 匹配不带尾斜杠的请求,重定向到带尾斜杠的地址并保留端口 rewrite ^/api/some-folder$ $scheme://$host:$server_port/api/some-folder/ permanent; location /api/some-folder/ { alias /some-folder/; default_type application/json; add_header Content-Type application/json; } } }
方案3:改用root替代alias(需调整目录结构)
如果可以调整文件存放路径,改用root配置更稳定,避免alias的重定向端口问题:
假设将JSON文件存放在/data/api/some-folder目录下,配置如下:
events {} http { server { index index.json; root /data; location /api/some-folder { default_type application/json; add_header Content-Type application/json; } } }
效果验证
修改配置后,访问http://localhost:8080/api/some-folder会正确重定向到http://localhost:8080/api/some-folder/(或直接返回内容),不会出现端口丢失的问题,和根路径/的访问行为一致。
内容的提问来源于stack exchange,提问作者Laurent Michel
相关产品推荐
相关产品推荐

