Laravel 5.6路由配置:强制URL包含语言参数
嘿,这个需求很常见!要实现所有URL强制带语言参数的重定向,咱们用Laravel的中间件就能完美解决,一步步来:
1. 创建「强制语言前缀」中间件
首先生成一个新的中间件,在终端运行:
php artisan make:middleware ForceLanguagePrefix
然后打开app/Http/Middleware/ForceLanguagePrefix.php,替换成下面的代码(适配Laravel 5.6的PHP版本,避免高版本字符串函数):
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\App; class ForceLanguagePrefix { public function handle($request, Closure $next) { // 第一步:排除静态资源(避免css/js/images这些被不必要的重定向) $excludedPaths = ['css', 'js', 'images', 'storage']; $currentPath = $request->path(); foreach ($excludedPaths as $path) { if (strpos($currentPath, "{$path}/") === 0 || $currentPath === $path) { return $next($request); } } // 第二步:定义你支持的语言列表 $supportedLanguages = config('app.supported_languages'); // 检查当前URL是否已经带了合法的语言前缀 $hasValidLangPrefix = false; foreach ($supportedLanguages as $lang) { if (strpos($currentPath, "{$lang}/") === 0 || $currentPath === $lang) { $hasValidLangPrefix = true; break; } } // 如果没有合法前缀,重定向到带默认语言的URL if (!$hasValidLangPrefix) { $defaultLang = App::getLocale(); // 拼接新URL,去掉多余的斜杠 $newUrl = rtrim("/{$defaultLang}/{$currentPath}", '/'); // 用301永久重定向,对SEO更友好 return redirect()->to($newUrl, 301); } return $next($request); } }
2. 注册中间件
打开app/Http/Kernel.php,把这个中间件加到web中间件组里(这样所有前端请求都会经过它):
protected $middlewareGroups = [ 'web' => [ // 保留原来的中间件,比如EncryptCookies、VerifyCsrfToken等 \App\Http\Middleware\ForceLanguagePrefix::class, ], // ...其他组 ];
3. 补充语言配置与路由语言设置
为了让语言逻辑更完整,咱们再做两个小配置:
3.1 配置支持的语言
打开config/app.php,添加支持的语言列表,同时确认默认语言:
// 默认语言 'locale' => 'en', // 新增:支持的语言数组 'supported_languages' => ['en', 'zh', 'es'], // 根据你的需求调整
3.2 路由语言设置中间件
再生成一个中间件来根据URL里的lang参数设置当前应用语言:
php artisan make:middleware SetLocale
打开app/Http/Middleware/SetLocale.php,写入:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\App; class SetLocale { public function handle($request, Closure $next) { $lang = $request->route('lang'); // 检查语言是否在支持列表里,非法语言就重定向到默认语言 if (in_array($lang, config('app.supported_languages'))) { App::setLocale($lang); } else { return redirect()->route('welcome', ['lang' => App::getLocale()]); } return $next($request); } }
然后在Kernel.php里注册这个路由中间件:
protected $routeMiddleware = [ // 保留原来的中间件,比如auth、guest等 'setlocale' => \App\Http\Middleware\SetLocale::class, ];
最后修改你的路由分组,加上这个中间件:
Route::prefix('{lang}')->middleware('setlocale')->group(function () { Route::get('/', 'HomeController@index')->name('welcome'); Route::get('/XYZ', 'HomeController@XXXXFunction')->name('another'); // 其他路由... });
测试一下!
现在访问不带语言前缀的URL,比如www.myapps.com/XYZ,会自动重定向到www.myapps.com/en/XYZ;如果访问非法语言前缀比如www.myapps.com/fr/XYZ,会重定向到www.myapps.com/en/XYZ,完美符合你的需求!
内容的提问来源于stack exchange,提问作者PHPer
相关产品推荐
相关产品推荐

