Skip to content

Commit

Permalink
Redirect regardless of protocol of url
Browse files Browse the repository at this point in the history
  • Loading branch information
thibautdeg committed Sep 24, 2024
1 parent 6022328 commit c4799fc
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/Http/Middleware/Redirects.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,32 @@ public function handle(Request $request, Closure $next)
$uri = Str::ascii($uri);
$requestUri = Str::ascii($requestUri);

$uriWithoutProtocol = $this->removeProtocol($uri);

$current = [
'full' => $uri,
'fullNoQuery' => Str::beforeLast($uri, '?'),
'fullWithTrailingSlash' => Str::finish($uri, '/'),
'fullWithoutTrailingSlash' => Str::replaceEnd('/', '', $uri),
'fullWithoutProtocol' => $uriWithoutProtocol,
'fullWithoutProtocolNoQuery' => Str::beforeLast($uriWithoutProtocol, '?'),
'path' => $requestUri,
'pathNoQuery' => Str::beforeLast($requestUri, '?'),
];

$activeRedirect = $urlMaps->first(function ($redirect) use ($current) {
$from = $redirect->clean_from;
$fromWithoutProtocol = preg_replace('~^https?://~', '', $from);

$hasWildcard = Str::contains($from, config('filament-redirects.route-wildcard', '*'));

return
($hasWildcard && Str::is($from, $current['path'])) ||
($hasWildcard && Str::is($from, $current['full'])) ||
(in_array($from, $current));
($hasWildcard && Str::is($fromWithoutProtocol, $current['fullWithoutProtocol'])) ||
(in_array($from, $current)) ||
($fromWithoutProtocol === $current['fullWithoutProtocol']) ||
($fromWithoutProtocol === $current['fullWithoutProtocolNoQuery']);
});

if (! $activeRedirect || $activeRedirect->clean_from === $activeRedirect->to) {
Expand All @@ -66,4 +74,15 @@ public function handle(Request $request, Closure $next)

return redirect($to, $activeRedirect->status);
}

private function removeProtocol(string $url): string
{
$parsedUrl = parse_url($url);

if (! isset($parsedUrl['scheme'])) {
return $url;
}

return Str::after($url, '://');
}
}

0 comments on commit c4799fc

Please sign in to comment.