在 NextJS 路由中的 slug 前面添加符号(例如 @) [英] Adding symbol (e.g. @) in front of slug in NextJS route

查看:45
本文介绍了在 NextJS 路由中的 slug 前面添加符号(例如 @)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 slug URL 前添加 @.例如:https://example.com/@username.

I am trying to add @ in front of a slug URL. For example: https://example.com/@username.

我试过 @[username].js 但这不起作用.

I tried @[username].js but that is not working.

这可能吗?

推荐答案

尝试使用 重写和一些正则表达式.Next.js 在后台使用 path-to-regexp.

Try using rewrites and some regex. Next.js uses path-to-regexp under the hood.

  async rewrites() {
    return [
      {
        source: '/:userId(@[a-zA-Z0-9]+)/:id*',
        destination: "/user/:userId/:id*",
      }
    ]
  }

在客户端使用 next/link:

<Link href={`@${userId}`}>
  <a>user</a>
</Link>

这篇关于在 NextJS 路由中的 slug 前面添加符号(例如 @)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆