diff --git a/docs/content/en/options-reference.md b/docs/content/en/options-reference.md index f3f90c4f9..e059d4b07 100644 --- a/docs/content/en/options-reference.md +++ b/docs/content/en/options-reference.md @@ -172,6 +172,13 @@ Set to a path to which you want to redirect users accessing the root URL (`/`). } ``` +## `redirectStatusCode` + +- type: `number` +- default: `302` + +Customize the status code to redirect unprefixed route to the default locale. + ## `differentDomains` - type: `boolean` diff --git a/src/helpers/constants.js b/src/helpers/constants.js index 7541a91e3..8d09aa4c3 100644 --- a/src/helpers/constants.js +++ b/src/helpers/constants.js @@ -42,6 +42,7 @@ export const DEFAULT_OPTIONS = { lazy: false, langDir: null, rootRedirect: null, + redirectStatusCode: 302, detectBrowserLanguage: { alwaysRedirect: false, cookieCrossOrigin: false, diff --git a/src/templates/plugin.main.js b/src/templates/plugin.main.js index c4d58478a..e26bb0e08 100644 --- a/src/templates/plugin.main.js +++ b/src/templates/plugin.main.js @@ -205,7 +205,7 @@ export default async (context) => { const storedRedirect = app.i18n.__redirect if (storedRedirect) { app.i18n.__redirect = null - return [302, storedRedirect] + return [options.redirectStatusCode, storedRedirect] } const resolveBaseUrlOptions = { diff --git a/test/module.test.js b/test/module.test.js index 9268bcc57..ccbf3d853 100644 --- a/test/module.test.js +++ b/test/module.test.js @@ -1075,6 +1075,36 @@ describe('with rootRedirect (object)', () => { }) }) +describe('with redirectStatusCode', () => { + /** @type {Nuxt} */ + let nuxt + + beforeAll(async () => { + const override = { + i18n: { + redirectStatusCode: 301, + strategy: 'prefix' + } + } + nuxt = (await setup(loadConfig(__dirname, 'basic', override, { merge: true }))).nuxt + }) + + afterAll(async () => { + await nuxt.close() + }) + + test('redirect unprefixed route /about-us to /en/about-us with correct status', async () => { + const requestOptions = { + followRedirect: false, + resolveWithFullResponse: true, + simple: false // Don't reject on non-2xx response + } + const response = await get('/about-us', requestOptions) + expect(response.statusCode).toBe(301) + expect(response.headers.location).toBe('/en/about-us') + }) +}) + describe('prefix_and_default strategy', () => { /** @type {Nuxt} */ let nuxt diff --git a/types/index.d.ts b/types/index.d.ts index 37a0c487c..870afd693 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -64,6 +64,7 @@ export interface Options extends BaseOptions { } parsePages?: boolean rootRedirect?: string | null | RootRedirectOptions + redirectStatusCode?: number routesNameSeparator?: string skipSettingLocaleOnNavigate?: boolean, sortRoutes?: boolean,