nginx中location里面的try_files配置导致Vue设置history模式下的请求丢失参数

Vue与Nginx配置:解决history模式下URL参数丢失问题
本文详细探讨了Vue应用在使用history模式时,由于Nginx配置不当导致的URL参数丢失问题。通过分析错误的`try_files`配置,指出在location块中`$uri/`后面的`index.html`缺失是关键原因。通过对比正确和错误的配置,揭示了`/vuecay/index.html`与`/vuecay/`的区别,以及它们如何影响参数传递。同时,文章还提到hash模式下无需额外配置,因此不会丢失参数。最后,提供了一级路径与多级路径在错误配置下的表现,总结了配置`try_files`时的注意事项。

nginx中location里面的try_files配置导致vue设置history模式下的请求丢失参数

背景描述:

在一次生产环境中,vue使用history模式在访问地址的参数会丢失,地址栏也会变成没有参数的地址,并且请求会发生301重定向。最后,发现vue从history模式改成hash模式可以解决参数丢失。但是产生301是nginx的问题,发现nginx配置的try_files有问题,所以会导致丢参数,try_files的配置是为了适配history模式。而nginx默认支持hash模式,不需要额外的配置,所以nginx默认hash是没有问题。最终,发现更改nginx的try_files也能让history模式的访问地址不丢参数。

复现history模式请求丢参数的情景

vue的模式设置为history:

mode: 'history'

有问题的location:

location /vuecay {
  root   html;
  index  index.html index.htm;
  # 匹配history模式,histoty模式必须要配置,hash模式可以不用配置
  #这里有两个坑:$uri/后面没有index.html,后面不会自动添加index.html,vuecay后面没有‘/’
  try_files $uri $uri/ /vuecay;
}

访问路径:

http://ip/vuecay/path1/path2?name=lucy

访问截图:

在这里插入图片描述

nginx访问日志:

"GET /vuecay/path1/path2?name=lucy HTTP/1.1" 301 162 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay --args: 
114.254.3.243 - - [12/Jul/2022:15:57:22 +0800] "GET /vuecay/ HTTP/1.1" 200 583 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/index.html --args:- 
"GET /vuecay/js/chunk-vendors.a0183049.js HTTP/1.1" 200 46638 "http://ip/vuecay/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/chunk-vendors.a0183049.js --args:- 
"GET /vuecay/js/app.a38bbab2.js HTTP/1.1" 200 1529 "http://ip/vuecay/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/app.a38bbab2.js --args:- 
114.254.3.243 - - [12/Jul/2022:15:57:22 +0800] "GET /vuecay/js/app.a38bbab2.js.map HTTP/1.1" 200 19888 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/app.a38bbab2.js.map --args:- 
"GET /vuecay/js/chunk-vendors.a0183049.js.map HTTP/1.1" 200 677730 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/chunk-vendors.a0183049.js.map --args:- 

可以看到地址栏发生改变,参数丢失,第一次请求会发生301重定向,第二次请求地址发生改变,页面也没获取到参数。

修改nginx配置解决参数丢失

上面的location的try_files的配置会导致history模式下的请求参数丢失:

location /vuecay {
  root   html;
  index  index.html index.htm;
  # 匹配history模式,histoty模式必须要配置,hash模式可以不用配置
  #这里有两个坑:$uri/后面没有index.html,后面不会自动添加index.html,vuecay后面没有‘/’
  try_files $uri $uri/ /vuecay;
}

改用这个location的try_files的配置就不会参数就丢失了。

location /vuecay {
  root   html;
  index  index.html index.htm;
  # 匹配history模式,histoty模式必须要配置,hash模式可以不用配置
  #这里有两个坑:$uri/后面没有index.html,后面不会自动添加index.html。
  #vuecay后面有‘/index.html’,等同于“/”,vuecay后面有“/”会自动在“/”后面添加index.html
  try_files $uri $uri/ /vuecay/index.html;
}

使用上面的访问路径:

http://ip/vuecay/path1/path2?name=cay

访问截图:

在这里插入图片描述

nginx访问日志:

"GET /vuecay/path1/path2?name=cay HTTP/1.1" 200 583 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/index.html --args: 
"GET /vuecay/js/app.a38bbab2.js HTTP/1.1" 200 1529 "http://ip/vuecay/path1/path2?name=cay" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/app.a38bbab2.js --args:- 
"GET /vuecay/js/chunk-vendors.a0183049.js HTTP/1.1" 200 46638 "http://ip/vuecay/path1/path2?name=cay" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/chunk-vendors.a0183049.js --args:- 
"GET /vuecay/js/app.a38bbab2.js.map HTTP/1.1" 200 19888 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/app.a38bbab2.js.map --args:- 
"GET /vuecay/js/chunk-vendors.a0183049.js.map HTTP/1.1" 200 677730 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/chunk-vendors.a0183049.js.map --args:- 

可以看出来,地址栏未发生变化,正常显示参数,请求不会发生301,页面正常显示获取的参数。

对比两种情形的location配置

history模式丢参数的location中的try_files配置:

location /vuecay {
  root   html;
  index  index.html index.htm;
  # 匹配history模式,histoty模式必须要配置,hash模式可以不用配置
  #这里有两个坑:$uri/后面没有index.html,后面不会自动添加index.html,vuecay后面没有‘/’
  try_files $uri $uri/ /vuecay;
}

history模式不丢参数的location中的try_files配置:

location /vuecay {
  root   html;
  index  index.html index.htm;
  # 匹配history模式,histoty模式必须要配置,hash模式可以不用配置
  #这里有两个坑:$uri/后面没有index.html,后面不会自动添加index.html。
  #vuecay后面有‘/index.html’,等同于“/”,vuecay后面有“/”会自动在“/”后面添加index.html
  try_files $uri $uri/ /vuecay/index.html;
}
  • 两者最大的区别是try_files最后面的vuecay是有带有了“/”。如果vuecay后面没带“/”代表的是资源,vuecay后面带“/”代表的是vuecay目录下的index.html。

  • 丢参数的location的try_files里的

    1. $uri
    2. $uri/
    3. /vuecay

    这三个配置是一样的意思。网上有人说$uri/是为了访问uri对应目录下的资源,但是测试中并不会自动查找index.html,当我手动添加index.html,才会去查找uri目录下的index.html。

    大家可以试试这个location:

    location /vuecay {
      root   html;
      index  index.html index.htm;
      # 匹配history模式,histoty模式必须要配置,hash模式可以不用配置
      # $uri/后面添加index.html
      try_files $uri $uri/index.html /vuecay;
    }
    

    测试结果和$uri/后面没有index.html完全不同。

  • 不丢参数的location的try_files里配置的是 /vuecay/index.html ,等价于/vuecay/,这里后面会自动添加index.html。而$uri/后面却 不会自动添加index.html,很奇怪。

hash模式解决参数丢失

mode: 'hash'

history模式丢参数的location的try_files的配置

location /vuecay {
  root   html;
  index  index.html index.htm;
  # 匹配history模式,histoty模式必须要配置,hash模式可以不用配置
  #这里有两个坑:$uri/后面没有index.html,后面不会自动添加index.html,vuecay后面没有‘/’
  try_files $uri $uri/ /vuecay;
}

访问路径:

http://ip/vuecay/#/path1/path2?name=cay

访问截图:

在这里插入图片描述

nginx访问日志:

"GET /vuecay/ HTTP/1.1" 200 583 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" "-" --uri:/vuecay/index.html --args:- 
"GET /vuecay/js/chunk-vendors.a0183049.js HTTP/1.1" 200 46638 "http://ip/vuecay/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/chunk-vendors.a0183049.js --args:- 
"GET /vuecay/js/app.5c197350.js HTTP/1.1" 200 1534 "http://ip/vuecay/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/app.5c197350.js --args:- 
"GET /vuecay/js/app.5c197350.js.map HTTP/1.1" 200 19920 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/app.5c197350.js.map --args:- 
"GET /vuecay/favicon.ico HTTP/1.1" 200 4286 "http://ip/vuecay/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" "-" --uri:/vuecay/favicon.ico --args:- 
"GET /vuecay/js/chunk-vendors.a0183049.js.map HTTP/1.1" 200 677730 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/chunk-vendors.a0183049.js.map --args:- 

可以看出地址栏也未变化,参数未丢失,页面正常显示参数,请求未发生301,也解决了参数丢失。

history丢参数,hash模式不丢参数的原因

因为nginx默认是支持hash模式的,不像history模式还得额外配置try_files。而且这里的location是出现问题的try_files的配置,所以history模式受影响,hash模式不受影响,即history模式会丢参数,hash模式不丢参数。

想要了解更多的信息nginx配置导致301的信息,可以看一下我写的另一篇文章:nginx配置导致的301和丢参数的问题的关系

拓展

上面使用的是三级路径(ip后面跟了三层目录/vuecay/path1/path2,我这里暂且称为三级路径):

http://ip/vuecay/path1/path2?name=cay

通过测试发现二级及以上路径,在vue为history模式并且错误的try_files配置中会丢失参数,但是一级路径却不会丢失参数

vue的模式设置为history:

mode: 'history'

history模式丢参数的location的try_files的配置:

location /vuecay {
  root   html;
  index  index.html index.htm;
  # 匹配history模式,histoty模式必须要配置,hash模式可以不用配置
  #这里有两个坑:$uri/后面没有index.html,后面不会自动添加index.html,vuecay后面没有‘/’
  try_files $uri $uri/ /vuecay;
}

测试的一级路径:

http://ip/vuecay?name=cay

访问截图:

在这里插入图片描述

nginx访问日志:

"GET /vuecay?name=cay HTTP/1.1" 301 162 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay --args:name=cay 
"GET /vuecay/?name=cay HTTP/1.1" 200 583 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/index.html --args:name=cay 
"GET /vuecay/js/chunk-vendors.a0183049.js HTTP/1.1" 200 46638 "http://ip/vuecay/?name=cay" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/chunk-vendors.a0183049.js --args:- 
"GET /vuecay/js/app.a38bbab2.js HTTP/1.1" 200 1529 "http://ip/vuecay/?name=cay" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/app.a38bbab2.js --args:- 
"GET /vuecay/js/app.a38bbab2.js.map HTTP/1.1" 200 19888 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/app.a38bbab2.js.map --args:- 
"GET /vuecay/js/chunk-vendors.a0183049.js.map HTTP/1.1" 200 677730 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-" --uri:/vuecay/js/chunk-vendors.a0183049.js.map --args:- 

可以看出来,地址栏发生变化(vuecay多了“/”),参数未丢失,请求会发生301,这是因为vuecay后面没有‘/’,所以发生301。

可见一级路径在错误的配置下,发生了301,但是却没有丢失参数,但是如果是二级路径及以上则会丢失参数,感兴趣可以尝试。

小结

  • try_files的错误配置会导致history模式下的请求的参数丢失,将try_files修改正确即可不丢失参数。
  • hash模式不需要额外配置try_files,所以不会丢失参数。
  • nginx配置的时候注意“/”,有“/” (目录下的资源,一般是index.html)和 无“/” (资源)是两种含义。
  • try_files中的$uri/ 虽然带有“/”,但是后面默认不带index.html,所以最好自己添加index.html。
  • 一级路径在vue是history模式,try_files配置有问题的情况下,不会丢失参数。

高亮的两条总结,是这次history请求丢参数的主要误区,大家一定要注意。如果大家测试的结果和我不同,欢迎一起讨论。

想要了解更多的信息nginx配置导致301的信息,可以看一下我写的另一篇文章:nginx配置导致的301和丢参数的问题的关系

附录:vue代码

我们构建简单的vue项目,使用路由,vue的相关代码如下。

Route.js

import VueRouter from "vue-router"
import HelloWorld1 from "./components/HelloWorld1"
import HelloWorld2 from "./components/HelloWorld2"
import HomeTest from "./components/HomeTest"

export default new VueRouter({
    mode: 'hash',
    base: '/vuecay/',
    deep: true,
    routes: [{
            //一级目录需要添加‘/’
            path: '/',
            component: HomeTest,
            //redirect: "/path1/path2",
            children: [{
                    path: 'path1',
                    component: HelloWorld1,
                    children: [{
                            //二级目录不需要加‘/’
                            path: 'path2',
                            component: HelloWorld2
                        }
                    ]
                }
            ]
        }
    ]
})

Vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  publicPath: '/vuecay/'
})

Main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from "vue-router"
import router from '@/router'

Vue.config.productionTip = false
Vue.use(VueRouter)

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
//import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
}
</script>

<style>

</style>

HomeTest.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
//import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
}
</script>

<style>

</style>

HelloWorld1.vue

<template>
  <div>
    welcome to path1,{{name}},访问的路径的参数:{{argName}}
    <div>
      <router-view/>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld1',
  data(){
    return {
      name: 'cay',
      argName: ''
    }
  },
  props: {
    msg: String
  },
  created () {
    console.log('path1:' + window.location.href)
    console.log('path1:' + this.$route.query.name)
    console.log(this.$route)
    console.log(this.$router)
    this.argName = this.$route.query.name
  }
}
</script>

<style scoped>

</style>

HelloWorld2.vue

<template>
  <div>
    welcome to path2,{{name}},访问的路径的参数:{{argName}}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld2',
  data(){
    return {
      name: 'lucy',
      argName: ''
    }
  },
  props: {
    msg: String
  },
  created () {
    console.log('path2:' + window.location.href)
    console.log('path2:' + this.$route.query.name)
    console.log(this.$route)
    console.log(this.$router)
    this.argName = this.$route.query.name
    //const x = { a: 8 };
    //console.log(JSON.stringify(x))
  }
}
</script>

<style scoped>

</style>

执行命令

npm run build

将编译后的文件部署到服务器上。部署的时候惨过一些坑后面会总结贴上链接。上面的步骤已经是排除坑之后的步骤了。

### `try_files` 指令的作用 `try_files` 是 Nginx 提供的一个用于检查文件是否存在并进行请求处理的指令。其主要作用是按照指定的顺序检查文件或路径是否存在,并使用第一个匹配的文件进行处理。如果所有指定的文件或路径都不存在,则会触发内部重定向到最后一个参数所指定的 URI 或返回特定的 HTTP 状态码 [^3]。 ### `try_files` 的语法格式 `try_files` 的基本语法如下: ```nginx try_files file ... uri; ``` 或者: ```nginx try_files file ... =code; ``` 其中,`file` 表示要检查的文件或路径,`uri` 表示当所有文件都不存在时,请求将被内部重定向到的 URI,`code` 表示当所有文件都不存在时直接返回的 HTTP 状态码,例如 404 [^3]。 ### `try_files` 的执行逻辑 `try_files` 按照从左到右的顺序依次检查每个文件是否存在: 1. 首先尝试匹配具体的文件路径; 2. 如果未找到文件,则尝试匹配目录(需在路径末尾加上 `/`); 3. 如果仍然未找到,则根据最后一个参数决定下一步操作: - 如果最后一个参数是 URI,则进行内部重定向到该 URI; - 如果最后一个参数是 `=code`,则直接返回指定的 HTTP 状态码 [^3]。 例如以下配置: ```nginx location / { try_files $uri $uri/ /index.html; } ``` 表示: - 首先尝试匹配请求的 URI 对应的静态文件; - 如果未找到,则尝试匹配该 URI 对应的目录; - 如果仍未找到,则内部重定向到 `/index.html`,由前端路由处理路径逻辑 [^1]。 该机制在 Vue.js前端框架使用 `history` 模式时尤为重要,因为刷新页面时 URL 并不对应实际的文件路径,需要统一重定向到入口文件 `index.html` [^2]。 ### `try_files` 的典型使用场景 #### 1. 前端单页应用(SPA)的路由支持 在部署 Vue、React 等单页应用时,使用 `history` 模式的路由会导致刷新页面时 Nginx 试图查找不存在的文件。通过以下配置可以解决此问题: ```nginx location / { try_files $uri $uri/ /index.html; } ``` 这样所有未找到的请求都会被重定向到 `index.html`,由前端路由接管 [^1]。 #### 2. 自定义 404 页面 可以通过 `try_files` 指定当文件不存在时返回 404 状态码或自定义错误页面: ```nginx location / { try_files $uri $uri/ =404; } ``` 该配置会在文件和目录都不存在时返回 404 错误 [^3]。 #### 3. 配合命名 location 使用 在某些复杂场景中,可以通过 `try_files` 调用命名 location 来实现更灵活的处理逻辑: ```nginx location / { try_files $uri $uri/ @router; } location @router { rewrite ^.*$ /index.html last; } ``` 该配置中,`@router` 是一个命名 location,当文件和目录都不存在时,请求会被转发到 `@router` 中定义的逻辑进行处理 [^4]。 ### 代码示例 以下是一个完整的 Nginx 配置示例,适用于部署 Vue 单页应用并支持 `history` 模式的路由: ```nginx server { listen 80; server_name example.com; root /var/www/my-vue-app; index index.html; location / { try_files $uri $uri/ /index.html; } location = /index.html { add_header Cache-Control "no-cache"; } location ~ \.js$ { expires 1y; } location ~ \.css$ { expires 1y; } } ``` 此配置中: - `try_files` 确保所有请求都会尝试匹配静态资源,否则返回 `index.html`; - 静态资源(`.js`、`.css`)设置了缓存策略; - 入口文件 `index.html` 设置为不缓存以确保获取最新版本 [^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值