Laravel 中的自定义 slug (URL)(使用 htaccess 是一个选项)
Custom slug (URL) in Laravel (using htaccess is an option)
我有这样的路线来自数据库
$cat_routes = App\User::list_routes();
foreach ($cat_routes as $route){
Route::get('/category/{'.$route->route.'}', CategoriesController@getCategoryByRoute');
}
要访问此类别,URL 将是:
domain.com/category/cars (or any category rather than cars)
是否有创建自定义 URL 或 slug 来更改 URL 的方法:
domain.com/cars (clothes, women, watches .... etc)
因此,当用户像这样单击 link 时 "domain.com/category/cars" 他将被重定向到 "domain.com/cars" 并且控制器继续将其作为类别处理 "category/cars".
函数如下所示:
public function getCategoryByRoute($category_route)
这可以从 Laravel 或 htaccess 完成吗?
请注意,我还有其他短 URL 类似
domain.com/gallery
domain.com/login
......
所以我不想重定向或缩短所有 URL。只是类别 URLs.
将路线放在最后:
Route::get('/gallery', '...');
Route::get('/login', '...');
Route::get('/category/{category}', 'CategoriesController@getCategoryByRoute');
Route::get('/{category}', 'CategoriesController@getCategoryByRoute');
当您在控制器中找不到该类别时,抛出一个异常。
您的部分回答与重定向有关。您可以在 Laravel 中代替 .htaccess。更好,因为如果你转移到 Nginx(或其他东西),你不必担心 "application logic in the htaccess"...
Route::get('/category/{categorySlug}', function($categorySlug) {
$redirectPath = sprintf('/%s', $categorySlug);
return redirect($redirectPath);
})->where('categorySlug', '[a-z0-9-]+');
说明:
- 它接受所有以“/category/x”开头的内容,其中 x 可以是范围 [a-z]、[0-9] 和破折号
中的任何内容
- 它使用该输入获取 redirectPath
- 它returns一个重定向
显然,您需要额外的路由来捕获这些重定向...
Route::get('/{categorySlug}', 'CategoriesController@getCategoryByRoute');
顺便说一句,此解决方案中的默认重定向状态是 302(临时移动)。如果你想要一个 301(永久移动):
redirect($redirectPath, 301);
我有这样的路线来自数据库
$cat_routes = App\User::list_routes();
foreach ($cat_routes as $route){
Route::get('/category/{'.$route->route.'}', CategoriesController@getCategoryByRoute');
}
要访问此类别,URL 将是:
domain.com/category/cars (or any category rather than cars)
是否有创建自定义 URL 或 slug 来更改 URL 的方法:
domain.com/cars (clothes, women, watches .... etc)
因此,当用户像这样单击 link 时 "domain.com/category/cars" 他将被重定向到 "domain.com/cars" 并且控制器继续将其作为类别处理 "category/cars".
函数如下所示:
public function getCategoryByRoute($category_route)
这可以从 Laravel 或 htaccess 完成吗?
请注意,我还有其他短 URL 类似
domain.com/gallery
domain.com/login
......
所以我不想重定向或缩短所有 URL。只是类别 URLs.
将路线放在最后:
Route::get('/gallery', '...');
Route::get('/login', '...');
Route::get('/category/{category}', 'CategoriesController@getCategoryByRoute');
Route::get('/{category}', 'CategoriesController@getCategoryByRoute');
当您在控制器中找不到该类别时,抛出一个异常。
您的部分回答与重定向有关。您可以在 Laravel 中代替 .htaccess。更好,因为如果你转移到 Nginx(或其他东西),你不必担心 "application logic in the htaccess"...
Route::get('/category/{categorySlug}', function($categorySlug) {
$redirectPath = sprintf('/%s', $categorySlug);
return redirect($redirectPath);
})->where('categorySlug', '[a-z0-9-]+');
说明:
- 它接受所有以“/category/x”开头的内容,其中 x 可以是范围 [a-z]、[0-9] 和破折号 中的任何内容
- 它使用该输入获取 redirectPath
- 它returns一个重定向
显然,您需要额外的路由来捕获这些重定向...
Route::get('/{categorySlug}', 'CategoriesController@getCategoryByRoute');
顺便说一句,此解决方案中的默认重定向状态是 302(临时移动)。如果你想要一个 301(永久移动):
redirect($redirectPath, 301);