如何在Nginx中配置子目录访问 解决/highlighter路径404报错问题
Nginx多路径入口404问题排查
问题描述
将html文件夹下的index.php设置为localhost:5555的访问入口,html/highlight文件夹下的index.php设置为localhost:5555/highlighter的访问入口时,根路径访问正常,但localhost:5555/highlighter返回404 Not Found。
目录结构
nginx │ ├── html │ ├── 50x.html │ ├── highlight │ │ ├── functions.php │ │ ├── icon.png │ │ ├── index.css │ │ ├── index.php │ └── index.php ├── nginx.exe
原始错误配置
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; server { listen 5555; server_name localhost; location / { root html; index index.php; } location /highlighter { root html/highlight; index index.php; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9123; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
错误原因
在多个location块中分别配置root参数导致路径拼接错误:Nginx的root规则会将请求URI直接拼接在root配置的路径后,请求/highlighter时,实际查找的文件路径为html/highlight/highlighter/index.php,与实际文件存放路径html/highlight/index.php不匹配,触发404。
修复方案
方案1:统一设置server级root(推荐)
将root配置从location块移出,放到server块全局生效:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 5555; server_name localhost; root "D:\Miscellaneous\nginxSites"; location / { index index.php; } location /highlighter { index index.php; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9123; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
方案2:使用alias替代root
如果需要保留不同路径独立根目录的配置,可将/highlighter对应的location块中的root替换为alias:
location /highlighter { alias html/highlight; index index.php; }
alias规则会将匹配到的URI前缀替换为alias配置的路径,请求/highlighter时会直接查找html/highlight/index.php,符合预期。
内容的提问来源于stack exchange,提问作者Frischmann
相关产品推荐
相关产品推荐

