Question

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?

Was it helpful?

Solution

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); 
});

OTHER TIPS

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); 
});

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

You can define a direct redirect route rule like this:

Route::redirect('foo', '/bar', 301);

Laravel 301 and 302 redirects using redirect() and route()

301 (permanent):

return redirect(route('events.show', $slug), 301);

302 (temporary):

By default, Route::redirect returns a 302 status code.

return redirect()->route('events.show', $slug);

Offical Laravel Docs,'Redirect Routes': https://laravel.com/docs/5.8/routing#redirect-routes

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top