Skip to content

Commit

Permalink
fix: Apply correct port when redirecting to another domain and the ap…
Browse files Browse the repository at this point in the history
…p doesn't run behind a proxy (#979 by @awkaiser-tr)

Fixes #658

----

# Contribution feedback

@amannn to preserve your desired formatting, this project would benefit
from an [EditorConfig](https://editorconfig.org/) or tool such as
[Prettier](https://prettier.io/)

---------

Co-authored-by: Jan Amann <[email protected]>
  • Loading branch information
awkaiser-tr and amannn authored Apr 5, 2024
1 parent 59cd8dc commit 485f59e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
11 changes: 8 additions & 3 deletions packages/next-intl/src/middleware/middleware.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,15 @@ export default function createMiddleware<Locales extends AllLocales>(
}

if (redirectDomain) {
urlObj.protocol =
request.headers.get('x-forwarded-proto') ?? request.nextUrl.protocol;
urlObj.port = '';
urlObj.host = redirectDomain;

if (request.headers.get('x-forwarded-host')) {
urlObj.protocol =
request.headers.get('x-forwarded-proto') ??
request.nextUrl.protocol;

urlObj.port = request.headers.get('x-forwarded-port') ?? '';
}
}

if (request.nextUrl.basePath) {
Expand Down
24 changes: 23 additions & 1 deletion packages/next-intl/test/middleware/middleware.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2451,7 +2451,16 @@ describe('domain-based routing', () => {
);
});

it('uses the correct port and protocol when being called from an internal address', () => {
it('uses the correct port and protocol', () => {
middleware(createMockRequest('/', 'fr', 'http://ca.example.com:3000'));
expect(MockedNextResponse.next).not.toHaveBeenCalled();
expect(MockedNextResponse.rewrite).not.toHaveBeenCalled();
expect(MockedNextResponse.redirect.mock.calls[0][0].toString()).toBe(
'http://ca.example.com:3000/fr'
);
});

it('uses the correct port and protocol when behind a proxy', () => {
middleware(
createMockRequest('/', 'fr', 'http://192.168.0.1:3000', undefined, {
'x-forwarded-host': 'ca.example.com',
Expand All @@ -2463,6 +2472,19 @@ describe('domain-based routing', () => {
expect(MockedNextResponse.redirect.mock.calls[0][0].toString()).toBe(
'https://ca.example.com/fr'
);

middleware(
createMockRequest('/', 'fr', 'http://192.168.0.1:3000', undefined, {
'x-forwarded-host': 'ca.example.com',
'x-forwarded-port': '4200',
'x-forwarded-proto': 'https'
})
);
expect(MockedNextResponse.next).not.toHaveBeenCalled();
expect(MockedNextResponse.rewrite).not.toHaveBeenCalled();
expect(MockedNextResponse.redirect.mock.calls[1][0].toString()).toBe(
'https://ca.example.com:4200/fr'
);
});

it('redirects requests for other locales', () => {
Expand Down

0 comments on commit 485f59e

Please sign in to comment.