Detect infinite HTTP redirect loop on server side
Asked Answered
E

2

5

Is there a way to detect infinite HTTP 3xx redirect loops on the server? (Not necessarily the exact moment when the client gives an error, as the number of redirects required for that is client-dependent, but log an error after, say, 10 continuous redirects.)

The redirects come from the application code in a LAMP environment. I can change the code, but don't want to change the URL so adding some sort of counter to it is out of the question. I suppose I could use the session to count the number of redirects and erase that count on each non-redirect request, but that is brittle because the session is shared between several browser windows. Is there another way (such as using some HTTP header which the browser would mirror back)?

Eau answered 13/3, 2012 at 11:22 Comment(2)
I created a Mozilla feature request asking for a better way to handle this problem.Eau
@brillout What more did you expect for an answer on this question? The answer is correct.Admission
U
8

There is no 'standard' way.

You should probably approach it with sessions. Only count urls that redirect, but also keep a timer, because you'd only want to trigger if the redirects happen in a very short timespan.

Of course, fixing the cause is much better than patching the symptoms.

Undergarment answered 13/3, 2012 at 11:43 Comment(0)
P
0

Redirect to page and send custom HTTP headers: Redirect to page and send custom HTTP headers

Maybe this will help(PHP in a LAMP env).

// Check if the custom header exists and get its value
$redirectCount = isset($_SERVER['HTTP_X_REDIRECT_COUNT']) ? intval($_SERVER['HTTP_X_REDIRECT_COUNT']) : 0;

// Increment the redirect count
$redirectCount++;

// Check if the threshold is reached
if ($redirectCount >= 10) {
    error_log("Error: Infinite redirect loop detected.");
}

// Set the custom header for the next redirect
header("X-Redirect-Count: $redirectCount");

// Perform the redirection
header("Location: new_destination.php");
exit();
Pagan answered 17/8, 2023 at 9:47 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.