【发布时间】:2019-01-29 14:43:57
【问题描述】:
在其他框架中,存在请求转发的概念,即请求可以在内部重定向到应用程序内的另一个控制器操作,而无需通过显式重定向响应用户。
对于电子商务示例,如果产品的 SEO 友好 URL 为 /red-shoes.html,则对该 URL 的请求将在内部转发到 /catalog/product/id/1234。用户将收到 200 响应代码,并且产品 ID 1234 的产品页面将呈现在 /red-shoes.html 的原始 URL。我试图避免的行为是发出 301 重定向到 /catalog/product/view/id/1234 并丢失友好的 URL。
如何在 Laravel (5.7) 中实现这一点?我可以引入一个中间件来拦截请求,但是在中间件中,我只能在应用程序内进行重定向。 redirect() 将 302 发送回用户,这是我不想要的。
namespace App\Http\Middleware;
use Closure;
use App\Rewrite;
class ProductForward
{
public function handle($request, Closure $next)
{
// make a lookup to see if URI in request matches a known product
$productId = Product::lookupRequest($request);
if ($productId) { // if matches, forward to product controller
return redirect()->route('catalog_product', ['id' => $productId]); // not desired
}
// if no match is found, continue on with the request
return $next($request);
}
}
作为后续,如果没有路由匹配,是否可以在路由完成后执行此查找?
例如,假设存在路由/login 以呈现登录页面。如果用户转到/login,则没有必要为此请求查找产品友好的 URL - 只需呈现登录页面。但是,如果用户访问/blue-shoe.html,并且这不是 Laravel 中的预定义路由,则执行产品查找并转发 after 应用程序路由但 before 呈现 404 .
【问题讨论】: