Skip to content

Commit fb36d83

Browse files
committed
Support for trailing / in urls by producing alternate version and checking the disk for both
refactored simple file checks to use a loop.
1 parent e12b962 commit fb36d83

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed

src/Http/Middleware/CheckForRedirects.php

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,25 +18,32 @@ class CheckForRedirects
1818
*/
1919
public function handle(Request $request, Closure $next, string ...$guards): Response
2020
{
21-
//Handle simple redirects
21+
// Grab uri, make alternate / permutation
2222
$uri = $request->getRequestUri();
23-
$b64 = base64_encode($uri);
24-
$toCheck = hash( 'sha512', $b64);
25-
26-
if (\Statamic\Facades\File::exists('content/alt-redirect/' . $toCheck . '.yaml')) {
27-
$redirect = Yaml::parse(\Statamic\Facades\File::get('content/alt-redirect/' . $toCheck . '.yaml'));
28-
if (!($redirect['sites'] ?? false) || (in_array(Site::current(), $redirect['sites']))) {
29-
return redirect(($redirect['to'] ?? '/'), $redirect['redirect_type'] ?? 301);
30-
}
23+
if (str_ends_with($uri, '/')) {
24+
$permuURI = substr($uri, 0, strlen($uri) - 1);
25+
} else {
26+
$permuURI = $uri . '/';
3127
}
3228

33-
if (\Statamic\Facades\File::exists('content/alt-redirect/' . $b64 . '.yaml')) {
34-
$redirect = Yaml::parse(\Statamic\Facades\File::get('content/alt-redirect/' . $b64 . '.yaml'));
35-
if (!($redirect['sites'] ?? false) || (in_array(Site::current(), $redirect['sites']))) {
36-
return redirect(($redirect['to'] ?? '/'), $redirect['redirect_type'] ?? 301);
29+
//Build all potential versions
30+
$possibleSimple = [];
31+
$possibleSimple[] = $b64 = base64_encode($uri);
32+
$possibleSimple[] = hash( 'sha512', $b64);
33+
$possibleSimple[] = $permuB64 = base64_encode($permuURI);
34+
$possibleSimple[] = hash( 'sha512', $permuB64);
35+
36+
//Check potentials
37+
foreach($possibleSimple as $simple) {
38+
if (\Statamic\Facades\File::exists('content/alt-redirect/' . $simple . '.yaml')) {
39+
$redirect = Yaml::parse(\Statamic\Facades\File::get('content/alt-redirect/' . $simple . '.yaml'));
40+
if (!($redirect['sites'] ?? false) || (in_array(Site::current(), $redirect['sites']))) {
41+
return redirect(($redirect['to'] ?? '/'), $redirect['redirect_type'] ?? 301);
42+
}
3743
}
3844
}
3945

46+
//Regex checks
4047
$data = new Data('redirect', true);
4148
foreach ($data->regexData as $redirect) {
4249
if (preg_match('#' . $redirect['from'] . '#', $uri)) {
@@ -47,6 +54,7 @@ public function handle(Request $request, Closure $next, string ...$guards): Resp
4754
}
4855
}
4956

57+
//No redirect
5058
return $next($request);
5159
}
5260
}

0 commit comments

Comments
 (0)