Skip to content

fix: don't follow redirects for rewrites #2423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions cypress/e2e/middleware/standard.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ describe('Standard middleware', () => {
cy.url().should('eq', `${Cypress.config().baseUrl}/shows/rewrite-external`)
})

it('doesnt follow redirects from rewritten page', () => {
cy.request({ url: '/rewrite-to-redirect', followRedirect: false }).then((response) => {
expect(response.status).to.eq(302)
expect(response.redirectedToUrl).to.eq('https://example.com/')
})
})

it('adds headers to static pages', () => {
cy.request('/shows/static/3').then((response) => {
expect(response.headers).to.have.property('x-middleware-date')
Expand Down
5 changes: 5 additions & 0 deletions demos/middleware/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ export async function middleware(req: NextRequest) {
return res
}

if (pathname.startsWith("/rewrite-to-redirect")) {
return NextResponse.rewrite('https://httpbin.org/redirect-to?url=https://example.com')
}

// skipMiddlewareUrlNormalize next config option is used so we have to try to match both html path and data blob path
if (pathname.startsWith('/request-rewrite') || pathname.endsWith('/request-rewrite.json')) {
// request.rewrite() should return the MiddlewareResponse object instead of the Response object.
Expand Down Expand Up @@ -174,6 +178,7 @@ export const config = {
'/cookies/:path*',
{ source: '/static' },
{ source: '/request-rewrite' },
{ source: '/rewrite-to-redirect' },
{ source: '/matcher-cookie' },
{ source: '/shows/((?!99|88).*)' },
{
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/src/templates/edge-shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ export const buildResponse = async ({
}
if (rewriteUrl.hostname !== baseUrl.hostname) {
// Netlify Edge Functions don't support proxying to external domains, but Next middleware does
const proxied = fetch(new Request(rewriteUrl.toString(), request))
const proxied = fetch(new Request(rewriteUrl.toString(), request), { redirect: 'manual' })
return addMiddlewareHeaders(proxied, res)
}
res.headers.set('x-middleware-rewrite', relativeUrl)
Expand Down