Laravel, how to redirect as 301 and 302

2019-03-10 16:38发布

I cannot find info for redirecting as 301/302 in the Laravel docs.

In my routes.php file I use:

Route::get('foo', function(){ 
    return Redirect::to('/bar'); 
});

Is this a 301 or 302 by default? Is there a way to set it manually? Any idea why this would be omitted from the docs?

4条回答
Deceive 欺骗
2楼-- · 2019-03-10 16:47

Whenever you are unsure, you can have a look at Laravel's API documentation with the source code. The Redirector class defines a $status = 302 as default value.

You can define the status code with the to() method:

Route::get('foo', function(){ 
    return Redirect::to('/bar', 301); 
});
查看更多
你好瞎i
3楼-- · 2019-03-10 16:49

I update the answer for Laravel 5! Now you can find on docs redirect helper:

return redirect('/home');

return redirect()->route('route.name');

As usual.. whenever you are unsure, you can have a look at Laravel's API documentation with the source code. The Redirector class defines a $status = 302 as default value (302 is a temporary redirect).

If you wish have a permanent URL redirection (HTTP response status code 301 Moved Permanently), you can define the status code with the redirect() function:

Route::get('foo', function(){ 
    return redirect('/bar', 301); 
});
查看更多
放我归山
4楼-- · 2019-03-10 17:03

You can define a direct redirect route rule like this:

Route::redirect('foo', '/bar', 301);
查看更多
倾城 Initia
5楼-- · 2019-03-10 17:04

martinstoeckli's answer is good for static urls, but for dynmaic urls you can use the following.

For Dynamic URLs

Route::get('foo/{id}', function($id){ 
    return Redirect::to($id, 301); 
});

Live Example (my use case)

Route::get('ifsc-code-of-{bank}', function($bank){ 
    return Redirect::to($bank, 301); 
});

This will redirect http://swiftifsccode.com/ifsc-code-of-sbi to http://swiftifsccode.com/sbi

One more Example

Route::get('amp/ifsc-code-of-{bank}', function($bank){ 
    return Redirect::to('amp/'.$bank, 301); 
});

This will redirect http://amp/swiftifsccode.com/ifsc-code-of-sbi to http://amp/swiftifsccode.com/sbi

查看更多
登录 后发表回答