Unverified Commit 8c3c2b7e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update redirect regexes to not match _next (#27143)

This updates redirects' regexes to not match `/_next` paths since this is currently unexpected and can easily cause a multi-match redirect to break loading client-side assets. This also fixes custom-routes not matching correctly when `trailingSlash: true/false` is used

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`

x-ref: https://github.com/vercel/next.js/discussions/24683
x-ref: [slack thread](https://vercel.slack.com/archives/CGU8HUTUH/p1626159845474000)
parent e0ff0504
...@@ -19,6 +19,7 @@ import { findPagesDir } from '../lib/find-pages-dir' ...@@ -19,6 +19,7 @@ import { findPagesDir } from '../lib/find-pages-dir'
import loadCustomRoutes, { import loadCustomRoutes, {
CustomRoutes, CustomRoutes,
getRedirectStatus, getRedirectStatus,
modifyRouteRegex,
normalizeRouteRegex, normalizeRouteRegex,
Redirect, Redirect,
Rewrite, Rewrite,
...@@ -330,6 +331,10 @@ export default async function build( ...@@ -330,6 +331,10 @@ export default async function build(
) )
} }
const restrictedRedirectPaths = ['/_next'].map((p) =>
config.basePath ? `${config.basePath}${p}` : p
)
const buildCustomRoute = ( const buildCustomRoute = (
r: { r: {
source: string source: string
...@@ -347,6 +352,14 @@ export default async function build( ...@@ -347,6 +352,14 @@ export default async function build(
sensitive: false, sensitive: false,
delimiter: '/', // default is `/#?`, but Next does not pass query info delimiter: '/', // default is `/#?`, but Next does not pass query info
}) })
let regexSource = routeRegex.source
if (!(r as any).internal) {
regexSource = modifyRouteRegex(
routeRegex.source,
type === 'redirect' ? restrictedRedirectPaths : undefined
)
}
return { return {
...r, ...r,
...@@ -356,7 +369,7 @@ export default async function build( ...@@ -356,7 +369,7 @@ export default async function build(
permanent: undefined, permanent: undefined,
} }
: {}), : {}),
regex: normalizeRouteRegex(routeRegex.source), regex: normalizeRouteRegex(regexSource),
} }
} }
......
...@@ -65,6 +65,22 @@ export function normalizeRouteRegex(regex: string) { ...@@ -65,6 +65,22 @@ export function normalizeRouteRegex(regex: string) {
return regex.replace(/\\\//g, '/') return regex.replace(/\\\//g, '/')
} }
// for redirects we restrict matching /_next and for all routes
// we add an optional trailing slash at the end for easier
// configuring between trailingSlash: true/false
export function modifyRouteRegex(regex: string, restrictedPaths?: string[]) {
if (restrictedPaths) {
regex = regex.replace(
/\^/,
`^(?!${restrictedPaths
.map((path) => path.replace(/\//g, '\\/'))
.join('|')})`
)
}
regex = regex.replace(/\$$/, '(?:\\/)?$')
return regex
}
function checkRedirect( function checkRedirect(
route: Redirect route: Redirect
): { invalidParts: string[]; hadInvalidStatus: boolean } { ): { invalidParts: string[]; hadInvalidStatus: boolean } {
...@@ -525,10 +541,14 @@ function processRoutes<T>( ...@@ -525,10 +541,14 @@ function processRoutes<T>(
}` }`
} }
} }
r.source = `${srcBasePath}${r.source}` r.source = `${srcBasePath}${
r.source === '/' && srcBasePath ? '' : r.source
}`
if (r.destination) { if (r.destination) {
r.destination = `${destBasePath}${r.destination}` r.destination = `${destBasePath}${
r.destination === '/' && destBasePath ? '' : r.destination
}`
} }
newRoutes.push(r) newRoutes.push(r)
} }
......
...@@ -18,6 +18,7 @@ import { ...@@ -18,6 +18,7 @@ import {
Rewrite, Rewrite,
RouteType, RouteType,
CustomRoutes, CustomRoutes,
modifyRouteRegex,
} from '../lib/load-custom-routes' } from '../lib/load-custom-routes'
import { import {
BUILD_ID_FILE, BUILD_ID_FILE,
...@@ -822,11 +823,24 @@ export default class Server { ...@@ -822,11 +823,24 @@ export default class Server {
...staticFilesRoute, ...staticFilesRoute,
] ]
const restrictedRedirectPaths = ['/_next'].map((p) =>
this.nextConfig.basePath ? `${this.nextConfig.basePath}${p}` : p
)
const getCustomRoute = ( const getCustomRoute = (
r: Rewrite | Redirect | Header, r: Rewrite | Redirect | Header,
type: RouteType type: RouteType
) => { ) => {
const match = getCustomRouteMatcher(r.source) const match = getCustomRouteMatcher(
r.source,
!(r as any).internal
? (regex: string) =>
modifyRouteRegex(
regex,
type === 'redirect' ? restrictedRedirectPaths : undefined
)
: undefined
)
return { return {
...r, ...r,
......
...@@ -15,13 +15,19 @@ export const customRouteMatcherOptions: pathToRegexp.TokensToRegexpOptions & ...@@ -15,13 +15,19 @@ export const customRouteMatcherOptions: pathToRegexp.TokensToRegexpOptions &
} }
export default (customRoute = false) => { export default (customRoute = false) => {
return (path: string) => { return (path: string, regexModifier?: (regex: string) => string) => {
const keys: pathToRegexp.Key[] = [] const keys: pathToRegexp.Key[] = []
const matcherRegex = pathToRegexp.pathToRegexp( let matcherRegex = pathToRegexp.pathToRegexp(
path, path,
keys, keys,
customRoute ? customRouteMatcherOptions : matcherOptions customRoute ? customRouteMatcherOptions : matcherOptions
) )
if (regexModifier) {
const regexSource = regexModifier(matcherRegex.source)
matcherRegex = new RegExp(regexSource, matcherRegex.flags)
}
const matcher = pathToRegexp.regexpToFunction(matcherRegex, keys) const matcher = pathToRegexp.regexpToFunction(matcherRegex, keys)
return (pathname: string | null | undefined, params?: any) => { return (pathname: string | null | undefined, params?: any) => {
......
...@@ -378,6 +378,17 @@ module.exports = { ...@@ -378,6 +378,17 @@ module.exports = {
destination: '/another?host=1', destination: '/another?host=1',
permanent: false, permanent: false,
}, },
{
source: '/:path/has-redirect-5',
has: [
{
type: 'header',
key: 'x-test-next',
},
],
destination: '/somewhere',
permanent: false,
},
] ]
}, },
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment