Nginx简单代理配置不生效,访问location /test路径返回404错误
问题根因
你配置中location /test块使用root html时,Nginx的root指令逻辑是将请求路径拼接在root指定的目录后,作为最终查找资源的路径。你访问localhost:81/test时,Nginx会尝试查找html/test/index.html文件,你没有创建对应test目录及文件,因此返回404;而访问根路径时会直接查找html/index.html,所以访问正常。
解决方案
根据你的需求,推荐以下三种配置方案,按需选择即可:
方案1:使用alias指令(地址栏不变,路径直接映射)
alias指令不会拼接请求路径,会直接将/test路径映射到指定的html目录下查找资源,符合你要同根路径展示相同内容的需求:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; server { listen 81 ; server_name localhost; location / { root html; index index.html index.htm; } location /test { # 替换root为alias alias html; index index.html index.htm; } } }
方案2:使用rewrite重写路径(地址栏不变,重写请求路径)
将/test开头的请求路径重写为根路径的请求,匹配根路径的location规则查找资源:
location /test { rewrite ^/test(.*)$ /$1 break; root html; index index.html index.htm; }
方案3:跳转至根路径(地址栏变为根路径,适合不需要保留/test路径的场景)
访问/test时直接跳转至根路径,资源加载逻辑完全复用根路径配置:
location /test { return 302 /; }
配置生效操作
修改配置后,在bash终端执行以下命令重载配置即可生效,无需重启服务:./nginx.exe -s reload
如果出现配置不生效的情况,可以先执行./nginx.exe -s stop关闭所有Nginx进程,再重新执行./nginx.exe启动服务即可。
内容的提问来源于stack exchange,提问作者Kim Vu
相关产品推荐
相关产品推荐

