Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Redirect every request in a Laravel app

I recently had to redirect every single request in a Laravel app. You might think that would be as easy as this:

Route::get('/', function() {
   return redirect('https://targetdomain.com');

But that’ll only redirect the “/” page. All other requests will return a 404. Here’s how redirect every single request:

Route::get('{any}', function() {
   return redirect('https://targetdomain.com');
})->where('any', '.*');

If you need to redirect all pages except “/”, you can do this:

Route::get('{anyExceptRoot}', function() {
   return redirect('https://targetdomain.com');
})->where('anyExceptRoot', '[^/]*');
Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band. He loves waffles and butterflies.
  • bramus

    This looks more like something one would do via `.htaccess` (or the like on other webservers), yet in some cases it might be a handy snippet indeed.

    • yeah, if redirecting to the same url no matter what, doing it via the webserver is a better idea. In my case the redirect url was, unlike the example, not hardcoded, but read from a db.

      • bramus

        Ergo “some cases” 🙂