Skip to content

Commit e59c617

Browse files
authored
fix: don't follow redirects for rewrites (#2423)
* chore: add failing test * fix: dont resolve redirects * fix: run middleware on /rewrite-to-redirect * fix: don't miss the trailing slash!
1 parent ffe5856 commit e59c617

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

cypress/e2e/middleware/standard.cy.ts

+7
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ describe('Standard middleware', () => {
2424
cy.url().should('eq', `${Cypress.config().baseUrl}/shows/rewrite-external`)
2525
})
2626

27+
it('doesnt follow redirects from rewritten page', () => {
28+
cy.request({ url: '/rewrite-to-redirect', followRedirect: false }).then((response) => {
29+
expect(response.status).to.eq(302)
30+
expect(response.redirectedToUrl).to.eq('https://example.com/')
31+
})
32+
})
33+
2734
it('adds headers to static pages', () => {
2835
cy.request('/shows/static/3').then((response) => {
2936
expect(response.headers).to.have.property('x-middleware-date')

demos/middleware/middleware.ts

+5
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ export async function middleware(req: NextRequest) {
3838
return res
3939
}
4040

41+
if (pathname.startsWith("/rewrite-to-redirect")) {
42+
return NextResponse.rewrite('https://httpbin.org/redirect-to?url=https://example.com')
43+
}
44+
4145
// skipMiddlewareUrlNormalize next config option is used so we have to try to match both html path and data blob path
4246
if (pathname.startsWith('/request-rewrite') || pathname.endsWith('/request-rewrite.json')) {
4347
// request.rewrite() should return the MiddlewareResponse object instead of the Response object.
@@ -174,6 +178,7 @@ export const config = {
174178
'/cookies/:path*',
175179
{ source: '/static' },
176180
{ source: '/request-rewrite' },
181+
{ source: '/rewrite-to-redirect' },
177182
{ source: '/matcher-cookie' },
178183
{ source: '/shows/((?!99|88).*)' },
179184
{

packages/runtime/src/templates/edge-shared/utils.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ export const buildResponse = async ({
265265
}
266266
if (rewriteUrl.hostname !== baseUrl.hostname) {
267267
// Netlify Edge Functions don't support proxying to external domains, but Next middleware does
268-
const proxied = fetch(new Request(rewriteUrl.toString(), request))
268+
const proxied = fetch(new Request(rewriteUrl.toString(), request), { redirect: 'manual' })
269269
return addMiddlewareHeaders(proxied, res)
270270
}
271271
res.headers.set('x-middleware-rewrite', relativeUrl)

0 commit comments

Comments
 (0)