使用正则表达式向 Laravel URL 路由添加通配符

问题描述 投票:0回答:1

我需要在 Laravel 中实现下面的 htaccess 通配符 URL 重写规则。

实际网址应该是这样的

http://test.com/products/mobile-phones/phone-model.html

与上述 URL 关联的 htaccess 规则。

RewriteRule ^/products/([A-Za-z\d\-\.]+)/([A-Za-z\d\-\.]+)$     product.php?category_name=$1&product_name=$2&retype=0   [L]

Laravel 路线

Route::get('/product-category/product-name.html', [ProductPageController::class,'index']);

我需要在每个 URL 中保留 .html 扩展名。

laravel url url-rewriting wildcard
1个回答
0
投票

如果只想加载html文件:

  1. 创建刀片文件(例如:welcome.blade.php)
  2. 在您的视图文件中添加 $page 变量如下:
{!! $page !!}
  1. 将您的 html 文件放在一个目录中(例如:resources/pages)
  2. 在您的路由文件(web.php)中添加这样的路由:
Route::get('{any}', function ($any) {
    return view('welcome' , ['page' => file_get_contents(__DIR__."/resources/pages/{$any}.html")]);
});

现在,如果您调用

http://test.com/products/mobile-phones/phone-model.html
url,将加载
phone-model.html
目录中的resources/pages/products/mobile-phones/文件。

© www.soinside.com 2019 - 2024. All rights reserved.