【问题标题】:How to remove trailing slash from url in nuxt.js?如何从 nuxt.js 中的 url 中删除尾部斜杠?
【发布时间】:2019-11-04 07:02:14
【问题描述】:

我正在寻找一种方法来重定向我的所有 URL,以便它们最后都没有斜线。 我试过https://www.npmjs.com/package/@nuxtjs/redirect-module,但它没有正确重定向。

redirect: [
    {
      from: '\/$',
      to: (from, req) => req.url.replace(/\/$/, '')
    }
  ],

比如改个这样的urlhttp://localhost:8080/item/test-slug/ 这个模块将我重定向到http://localhost:8080/item/test-slug/item/test-slug

欢迎任何见解。谢谢!

【问题讨论】:

  • 用 ?fbclid= 寻找相同的结果,还没有结果...

标签: nuxt.js


【解决方案1】:

我已经使用自定义中间件解决了这个问题。它重定向到最后没有斜杠的 url。

创建src/middleware/trailingSlashRedirect.js

export default function ({ route, redirect }) {
  if (route.path !== '/' && route.path.endsWith('/')) {
    const { path, query, hash } = route;
    const nextPath = path.replace(/\/+$/, '') || '/';
    const nextRoute = { path: nextPath, query, hash };

    redirect(nextRoute);
  }
}

nuxt.config.js注册:

export default {
  ...
  router: {
    middleware: 'trailingSlashRedirect',
  },
}

所以你不应该使用任何模块来解决这个问题。我认为这比使用第三方库要好得多。

【讨论】:

  • 似乎只在将trailingSlash: false 添加到路由器时才有效。否则发生错误(关于重复重定向)
  • @tmarois 你不需要加trailingSlash: false,由于我上面提到的自定义中间件,不会发生重复重定向
  • 谢谢你,与我当前使用 trailingSlash 的设置完美配合:false
【解决方案2】:

您可以通过以下方式使用 Nuxt 最新版本(自 v2.10 起可用)删除尾部斜杠: https://nuxtjs.org/api/configuration-router/#trailingslash

trailingSlash : Type: Boolean or undefined
Default: undefined
Available since: v2.10
ex:
router: {
  trailingSlash: false
}

或者使用旧版本的 Nuxt 可以使用 nuxt-trailingslash-module https://www.npmjs.com/package/nuxt-trailingslash-module

npm i nuxt-trailingslash-module

【讨论】:

  • 我试过了。 trailingSlash: false 只是不起作用。不管是什么版本
【解决方案3】:

所以到目前为止我发现的唯一解决方案并不完美。

使用redirect-module,我在重定向列表顶部添加了以下内容:

{
  // eslint-disable-next-line
  from: '(?!^\/$|^\/[?].*$)(.*\/[?](.*)$|.*\/$)',
  to: (from, req) => {
    const base = req._parsedUrl.pathname.replace(/\/$/, '');
    const search = req._parsedUrl.search;
    return base + (search != null ? search : '');
  }
},

同样在 nuxt.config.js 中,我确保添加了尾部斜杠配置。 (See the doc)

router: {
  trailingSlash: false
},

注意: 它使用查询参数重定向所有以'/' 结尾的URL,但它与主页'/' 不匹配(似乎以某种方式处理)

以下内容将重定向以下内容:

  • '/blog/''/blog'
  • '/blog/?a=b''/blog?a=b'
  • '/blog/foo/''/blog/foo'
  • '/blog/foo/?a=b''/blog/foo?a=b'
  • '/''/'。 --> 不会工作
  • '/?a=b''/?a=b'。 --> 不会工作

我做了一个测试列表available here


正则表达式的解释

这可能并不完美,因为我不是正则表达式专家,但是:

'(?!^\/$|^\/[?].*$)(.*\/[?](.*)$|.*\/$)'

它被破坏了 2 部分:1 个排除和 1 个包含。

排除:(?!^\/$|^\/[?].*$),包括检查以排除独立尾随逗号 (/) 或带有查询字符串 /?foo=bar 路由的独立尾随逗号。主要用于首页。

包含:(.*\/[?](.*)$|.*\/$),包括检查逗号 (/blog/) 或带有查询字符串的尾随逗号 (/blog/?foo=bar)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2015-05-09
    相关资源
    最近更新 更多