Created
September 3, 2024 08:06
-
-
Save fjahn/931de6710f3399482e6122ab2d48988c to your computer and use it in GitHub Desktop.
Laravel Middleware to redirect users to currently configured app url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\Request; | |
use Symfony\Component\HttpFoundation\Response; | |
class EnsureAppUrl | |
{ | |
private readonly string $expectedHost; | |
public function __construct() | |
{ | |
$this->expectedHost = $this->getExpectedHost(); | |
} | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next | |
*/ | |
public function handle(Request $request, Closure $next): Response | |
{ | |
if ($request->method() !== 'GET') | |
return $next($request); | |
$currentHost = $request->host(); | |
if ($currentHost === $this->expectedHost) | |
return $next($request); | |
$newUrl = str_replace_first($currentHost, $this->expectedHost, $request->fullUrl()); | |
return redirect($newUrl, status: 301); | |
} | |
private function getExpectedHost(): string | |
{ | |
$appUrl = config('app.url'); | |
return parse_url($appUrl, PHP_URL_HOST); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment