在 Nginx 配置中,$uri 是一个 内置变量,表示当前请求的 URI(不包括查询参数)。
解析 try_files $uri $uri/ /index.html;
这一行的作用是:
-
尝试访问
$uri—— 直接匹配请求的 URI(如/about.html)。 -
尝试访问
$uri/—— 如果$uri是一个目录,则尝试访问该目录(如/blog/)。 -
回退到
/index.html—— 如果前两步都失败,则返回index.html(用于单页应用,如 Vue、React 前端项目)。
示例
请求 /about.html
-
$uri=/about.html - 如果
/usr/share/nginx/webroot/about.html存在,返回该文件。 - 否则,返回
/index.html。
请求 /blog/
-
$uri=/blog/ - 如果
/usr/share/nginx/webroot/blog/目录存在,Nginx 会尝试查找默认的index.html(除非index指定了其他文件)。 - 否则,返回
/index.html。
请求 /nonexistent
-
$uri=/nonexistent -
/usr/share/nginx/webroot/nonexistent不存在 -
/usr/share/nginx/webroot/nonexistent/不存在 - 退而求其次,返回
/usr/share/nginx/webroot/index.html(适用于 SPA 单页应用,前端路由会处理这个路径)。
总结
-
$uri代表请求的路径(不带查询参数)。 -
try_files用于按顺序查找可用资源,如果找不到,就回退到index.html。 - 这种配置常用于 前后端分离 项目,保证前端路由能正确解析。
🚀 如果你在部署 Vue、React、Angular 等前端应用,这个写法是标准方案!
在 Nginx 配置中,$uri 代表当前请求的路径(不带查询参数)。如果 try_files $uri $uri/ /index.html; 处理一个目录后仍然是目录,例如 /blog/productlist/,它的匹配规则如下:
匹配逻辑
-
尝试
$uri直接匹配文件$uri = /blog/productlist- Nginx 查找
/usr/share/nginx/webroot/blog/productlist是否是一个文件。 - 如果是文件,直接返回该文件。
-
尝试
$uri/作为目录$uri = /blog/productlist/- Nginx 现在查找
/usr/share/nginx/webroot/blog/productlist/目录。 -
如果这个目录存在,并且
index.html存在,则返回index.html(Nginx 默认会尝试/blog/productlist/index.html)。
-
如果前两步都失败,则回退到
/index.html- 这通常用于 前端单页应用(SPA),让 Vue/React/Angular 的路由来处理 URL。
示例 1:有 index.html 的目录
假设目录 /usr/share/nginx/webroot/blog/productlist/ 存在,并且有 index.html:
- 访问
/blog/productlist-
$uri = /blog/productlist,它是个目录,不是文件。 -
$uri/ = /blog/productlist/,它是个目录,Nginx 查找/blog/productlist/index.html并返回它。
-
示例 2:目录没有 index.html
如果 /usr/share/nginx/webroot/blog/productlist/ 没有 index.html,那么:
- 访问
/blog/productlist-
$uri = /blog/productlist,是目录,不匹配。 -
$uri/ = /blog/productlist/,仍然是目录,但没有index.html。 -
Nginx 退而求其次,返回
/index.html,通常用于 前端路由处理。
-
示例 3:目录不存在
如果 /usr/share/nginx/webroot/blog/productlist/ 整个目录都不存在:
- 访问
/blog/productlist-
$uri = /blog/productlist,找不到。 -
$uri/ = /blog/productlist/,找不到。 -
最终返回
/index.html(适用于前端路由)。
-
总结
-
/blog/productlist如果是文件,直接返回文件内容。 -
/blog/productlist/如果是目录且有index.html,则返回/blog/productlist/index.html。 -
/blog/productlist/如果目录存在但没有index.html,Nginx 可能返回 403(除非配置autoindex on;)。 -
如果
/blog/productlist/不存在,则返回/index.html(适用于前端单页应用)。
🚀 这种方式适用于 SPA 项目(Vue/React),让前端路由接管 URL 解析!