You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt.js i18n默认语言路由无需重定向的配置问题

解决方案

要实现默认语言(法语)无需URL前缀直接访问且不触发重定向,你需要调整@nuxtjs/i18n的核心配置,具体如下:

关键配置修改

1. 切换路由策略

将strategy从prefix改为prefix_except_default,这个策略会让默认语言的URL不带语言前缀,其他语言保留前缀,正好匹配你的需求。

2. 优化浏览器语言检测逻辑

保留detectBrowserLanguage的redirectOn: 'root'配置,确保仅在访问根路径时触发浏览器语言检测重定向,非根路径的无前缀URL直接使用默认语言返回内容。

修改后的完整配置

import { defineNuxtConfig } from 'nuxt/config'

export default defineNuxtConfig({
  // 其他配置...
  i18n: {
    detectBrowserLanguage: {
      useCookie: true,
      cookieCrossOrigin: true,
      cookieKey: 'i18n_redirected',
      redirectOn: 'root'
    },
    strategy: 'prefix_except_default', // 核心修改:默认语言不带前缀
    locales: [
      { name: 'English', code: 'en', iso: 'en-US', dir: 'ltr', file: 'en.json' },
      { name: 'Français', code: 'fr', iso: 'fr-FR', dir: 'ltr', file: 'fr.json' },
      { name: 'العربية', code: 'ar', iso: 'ar-AR', dir: 'rtl', file: 'ar.json' },
    ],
    defaultLocale: 'fr',
    vueI18n: './i18n.config.ts'
  },
  // 其他配置...
});

配置说明

  • prefix_except_default:该策略下,默认语言(fr)的路由直接使用无前缀形式(如/place),其他语言则使用带前缀的路由(如/en/place、/ar/place),且不会对无前缀的默认语言URL触发重定向。
  • redirectOn: 'root':仅当用户访问根路径(/)时,才会根据浏览器语言设置重定向到对应语言页面;访问具体无前缀路径(如/place)时,直接返回默认语言内容,地址栏不会发生变化。

额外验证步骤

  1. 清除浏览器缓存和i18n_redirected相关Cookie,避免旧配置残留影响。
  2. 重启Nuxt开发服务器,确保新配置生效。
  3. 测试访问/place,确认直接显示法语内容且地址栏无重定向跳转;访问/en/place则正常显示英文内容。

内容的提问来源于stack exchange,提问作者Merouane Amqor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 18:18:17