Next.js: Regex Path Matching for Redirects

Created on 30 Jul 2020  路  4Comments  路  Source: vercel/next.js

Feature request

Is your feature request related to a problem? Please describe.

A common URL pattern for blogs and websites coming from Wordpress is /year/month/day/slug. To redirect pages that match this to a different page, the path matching would look like this:

{
  source: '/:year/:month/:day/:post',
  destination: '/blog/:post',
  permanent: true,
},

This however matches generated Next.js files (for example, /_next/static/css/b9c315e24bcc3c2b5b54.css which results in effectively breaking the built website (dev mode doesn't match this pattern).

Describe the solution you'd like

By adding more finegrained matchers like Regex strings, you could restrict the matching to look for numbers only. Using the example above, in the vercel.json file I can currently write "\/\\d{4}\/\\d{2}\/\\d{2}\/(.+)\/?" to only match blog posts.

Describe alternatives you've considered

I can achieve this by leveraging platform-specific files such as vercel.json but it would be nice to have support for this out of the box!

story documentation

Most helpful comment

Hi, this is supported in Next.js, see the example redirect below for matching all routes except _next. Note: the rewrites and redirects support in vercel.json matches Next.js' built-in support

module.exports = {
  redirects() {
    return [
      {
        source: '/:year((?!_next).*)/:month/:day/:post',
        destination: '/blog/:post',
        permanent: false
      }
    ]
  }
}

All 4 comments

Hi, this is supported in Next.js, see the example redirect below for matching all routes except _next. Note: the rewrites and redirects support in vercel.json matches Next.js' built-in support

module.exports = {
  redirects() {
    return [
      {
        source: '/:year((?!_next).*)/:month/:day/:post',
        destination: '/blog/:post',
        permanent: false
      }
    ]
  }
}

Oh awesome! I didn't see mentions of that in the documentation, will give it a shot!

It does look like this isn't documented, I opened a PR to mention this support here, thanks for bringing this up!

Looks great, thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rauchg picture rauchg  路  208Comments

baldurh picture baldurh  路  74Comments

matthewmueller picture matthewmueller  路  102Comments

nickredmark picture nickredmark  路  60Comments

dunika picture dunika  路  58Comments