如何将以下网址重定向到小写网址?
http://domain.com/City/really-long-slug-from-db/photos
http://domain.com/city/Really-Long-Slug-From-Db/photos
http://domain.com/City/really-long-slug-from-db/Photos
至
http://domain.com/city/really-long-slug-from-db/photos
这是我的路线:
Route::any('/{city}/{slug}/{page?}', array( 'as' => 'slug-page', function($city, $slug, $page="info"){ return View::make('default.template.'.$page) ->with('city', $city) ->with('page',$page) ->with('slug', $slug); } )) ->where( array( 'city' => '[a-z ]+', 'page' => '[a-z-]+', 'slug' => '(about|photos|videos)' ));
目前我使用正则表达式[a-z-]+
只匹配较小的字符串字符串,并且NotFoundHttpException
出于显而易见的原因抛出.如何在不区分大小写的字符串中接受所有这些参数,并在Laravel 5.1中将301重定向(以避免重复的URL)到较小的案例URL?
您可以使用路由中间件轻松完成此操作.中间件应检查路径中是否有任何大写字符并重定向到小写版本.
首先,定义中间件类:
class RedirectToLowercase { public function handle($request, Closure $next) { $path = $request->path(); $pathLowercase = strtolower($path); // convert to lowercase if ($path !== $pathLowercase) { // redirect if lowercased path differs from original path return redirect($pathLowercase); } return $next($request); } }
然后在Kernel.php中注册新的中间件:
protected $routeMiddleware = array( // ... some other middleware classes ... 'lowercase' => 'App\Http\Middleware\RedirectToLowercase' );
最后,将中间件应用到您的路线:
Route::any('/{city}/{slug}/{page?}', array( 'as' => 'slug-page', 'middleware' => 'lowercase', function() { // your code }) );