问题
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?
回答1:
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);
});
回答2:
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);
});
回答3:
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
回答4:
You can define a direct redirect route rule like this:
Route::redirect('foo', '/bar', 301);
回答5:
As of Laravel 5.8 you can specify Route::redirect
:
Route::redirect('/here', '/there');
By default that will redirect with 302 HTTP status code, meaning temporary redirect. If the page is permanently moved you can specify 301 HTTP status code:
Route::permanentRedirect('/here', '/there');
/* OR */
Route::redirect('/here', '/there', 301);
Laravel docs: https://laravel.com/docs/5.8/routing#redirect-routes
来源:https://stackoverflow.com/questions/19964663/laravel-how-to-redirect-as-301-and-302