Skip to content

Instantly share code, notes, and snippets.

@fjahn
Created September 3, 2024 08:06
Show Gist options
  • Save fjahn/931de6710f3399482e6122ab2d48988c to your computer and use it in GitHub Desktop.
Save fjahn/931de6710f3399482e6122ab2d48988c to your computer and use it in GitHub Desktop.
Laravel Middleware to redirect users to currently configured app url
<?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