{"record":{"id":"86a3b690b49e5a2a","repo":"psf/requests","slug":"exceeded-self-max-redirects-redirects","errorCode":null,"errorMessage":"Exceeded {self.max_redirects} redirects.","messagePattern":"Exceeded (.+?) redirects\\.","errorType":"exception","errorClass":"TooManyRedirects","httpStatus":null,"severity":"error","filePath":"src/requests/sessions.py","lineNumber":217,"sourceCode":"\n        hist: list[Response] = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            resp.history = hist[:]\n            hist.append(resp)\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()","sourceCodeStart":199,"sourceCodeEnd":235,"githubUrl":"https://github.com/psf/requests/blob/8068356288978c4f54661ae6f95afe0e0831885e/src/requests/sessions.py#L199-L235","documentation":"Raised by Session.resolve_redirects() when the number of HTTP redirects in a chain reaches or exceeds session.max_redirects (default 30). This is a safety mechanism to prevent infinite redirect loops. The response object is attached so the caller can inspect the last redirect response.","triggerScenarios":"A URL that redirects more than 30 times (default); a redirect loop where URL A → URL B → URL A indefinitely; a misconfigured server with circular Location headers; a login flow with many intermediary redirects.","commonSituations":"Server-side redirect loop after authentication changes; cookie handling causing repeated redirects to a login page; migrating URLs without updating redirect chains; CDN misconfiguration creating circular redirects between HTTP and HTTPS.","solutions":["Investigate the redirect chain with allow_redirects=False to inspect each Location header manually.","If the redirect count is legitimately high, increase session.max_redirects to a safe ceiling.","Fix the server-side redirect loop — exceeding 30 redirects almost always indicates a bug."],"exampleFix":"# before\nresp = session.get(url)  # TooManyRedirects\n\n# after — diagnose the chain\nresp = session.get(url, allow_redirects=False)\nprint(resp.status_code, resp.headers.get('Location'))\n\n# or increase the limit if legitimate\nsession.max_redirects = 50","handlingStrategy":"try-catch","validationCode":"session.max_redirects = 10  # set a sensible limit for your use case","typeGuard":null,"tryCatchPattern":"try:\n    resp = session.get(url)\nexcept requests.TooManyRedirects as e:\n    logger.error(f'Redirect chain exceeded limit. Last URL: {e.response.url}')\n    # Debug with allow_redirects=False\n    resp = session.get(url, allow_redirects=False)","preventionTips":["Use allow_redirects=False to inspect redirect chains when debugging.","Set session.max_redirects to a reasonable limit for your application.","Check for redirect loops in server configuration (especially auth/login flows).","Ensure cookie handling isn't causing repeated auth redirects."],"tags":["redirect","too-many-redirects","session","redirect-loop","network"],"backgroundTag":null,"analyzedSha":"8068356288978c4f54661ae6f95afe0e0831885e","analyzedAt":"2026-08-11T20:11:09.238Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}