nginx路径相关配置汇总

一、root和alias的区别

root是将root配置的路径和location配置的路径拼接;alias则是用alias的路径替换location配置的路径

bash 复制代码
# 返回localhost:port/html/test/index.html的文件 
location ^~ /test/ { 
    root html/;
    index index.html index.htm;
} 
# 返回localhost:port/html/test/index.html的文件 
location ^~ /test/ { 
    alias html/test/; 
    index index.html index.htm;
}

二、 location路径末尾有无/的区别

1.location末尾没有/,则以结尾路径进行模糊匹配,配置location /test/a,则可以匹配/test/a,/test/a/,/test/a/b,/test/abc
  • ✅ /test/a
  • ✅ /test/a/
  • ✅ /test/a/b
  • ✅ /test/abc(是的,也会匹配!)
bash 复制代码
lication /test/a {
    alias html/test/;
    index index.html index.htm;
}
2.location末尾有/,则以结尾路径进行精确匹配,配置location /test/a/,则可以匹配/test/a/,/test/a/b,不能匹配/test/a,/test/abc
  • ✅ /test/a/
  • ✅ /test/a/b
  • ❌ /test/a(严格来说不匹配,但有时会301重定向到有/的版本)
  • ❌ /test/abc
bash 复制代码
lication /test/a/ {
    alias html/test/;
    index index.html index.htm;
}

使用 proxy_pass 配置反向代理,在匹配到 location 配置的 URL 路径后,转发请求到 proxy_pass 配置额 URL,方向代理后的地址与 proxy_pass 路径末尾是否有"/"有关;

三、proxy_pass 路径末尾有无/的区别

1.proxy_pass 路径末尾配置/表示绝对路径,当请求匹配到/api/时,会直接将替换为 proxy_pass 的路径
javascript 复制代码
location   /api/  {
      proxy_pass    http://127.0.0.1:8080/;
}

请求 http://xxx/api/get,将会被 nginx 转发请求到http://127.0.0.1:8080/get(未附加/api/路径)。

2.proxy_pass 路径末尾没有/表示相对路径,当请求匹配到/api/时,会拼接 proxy_pass 的路径
javascript 复制代码
location   /api/  {
      proxy_pass    http://127.0.0.1:8080;
}

请求 http://xxx/api/get,将会被 nginx 转发请求到http://127.0.0.1:8080/api/get(拼接/api/路径)。

四、try_files 当配置资源请求失败时,尝试访问try_files路径下的资源

由于vue项目是SPA,只有一个html页面,当使用项目history模式,在访问子路由时,刷新页面会nginx报错404,则需要配置try_files,使得nginx在访问资源失败时,尝试访问try_files配置的资源路径;

bash 复制代码
lication /test/ {
    alias html/test/;
    index index.html index.htm;
    try_files $uri $uri/ /test/index.html;
}

项目访问localhost:port/test/根路径则可以正常访问,当访问子路由localhost:port/test/home刷新页面之后则请求不到资源,则依次读取try_files下的资源,$uri指代我们访问的路径/test/home,访问失败,则最终访问我们配置的/test/index.html,返回资源。

相关推荐
PC2005-cloud9 小时前
Nginx 学习笔记:Server 块配置详解,域名路由与多站点部署实战
nginx
zach9 小时前
Vue/React SPA 打包部署后,子路由刷新 401 未登录问题彻底解决
前端·nginx·next.js
yume_sibai12 小时前
02-Nginx进阶配置完全指南(性能优化 + 安全配置 + 缓存配置 + WebSocket代理)
nginx·安全·性能优化
阿狗童鞋12 小时前
Nginx反向代理与负载均衡实战指南
运维·nginx·负载均衡
Lsetea1 天前
OpenSSL verify报error 20:CAfile、fullchain与本地信任链分层排查
nginx·https·ssl证书·openssl·证书链
qq_394562001 天前
【在Linux上升级nginx】
linux·服务器·nginx
冬、不眠的夜1 天前
分享一下 nginx 配置一个简单的 web 网站
nginx
孤狼GPT1 天前
ChatGPT、Codex排查实录:接口偶发502/504,应用日志却没有报错,到底该查哪一层?
nginx·codex·chatgptplus·chatgptpro·接口排查
2601_962381132 天前
历史视频朝代更替动效怎么做?把 AE 关键帧换成 AI 分镜动画的实战拆解
人工智能·nginx·音视频
数据杂坛2 天前
【Python程序开发系列】一文搞清楚Gunicorn以及和Nginx的区别
python·nginx·gunicorn