{"record":{"id":"6667c94eca6ad1f3","repo":"ultralytics/yolov5","slug":"too-many-redirects-while-fetching-url","errorCode":null,"errorMessage":"Too many redirects while fetching {url}","messagePattern":"Too many redirects while fetching (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"models/common.py","lineNumber":840,"sourceCode":"    except socket.gaierror as e:\n        raise ValueError(f\"Could not resolve hostname '{hostname}': {e}\") from e\n    for _family, _type, _proto, _canonname, sockaddr in results:\n        addr = ipaddress.ip_address(sockaddr[0])\n        if addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_reserved or addr.is_multicast:\n            raise ValueError(f\"Blocked request to internal address: {addr}\")\n\n\ndef _request_ssrf_url(url: str, max_redirects: int = 5):\n    \"\"\"Fetch a URL after validating each resolved redirect target.\"\"\"\n    session = requests.Session()\n    for _ in range(max_redirects + 1):\n        _validate_ssrf_url(url)\n        response = session.get(url, stream=True, allow_redirects=False)\n        if not response.is_redirect:\n            return response\n        url = urljoin(response.url, response.headers[\"location\"])\n        response.close()\n    raise ValueError(f\"Too many redirects while fetching {url}\")\n\n\nclass AutoShape(nn.Module):\n    \"\"\"AutoShape class for robust YOLOv5 inference with preprocessing, NMS, and support for various input formats.\"\"\"\n\n    conf = 0.25  # NMS confidence threshold\n    iou = 0.45  # NMS IoU threshold\n    agnostic = False  # NMS class-agnostic\n    multi_label = False  # NMS multiple labels per box\n    classes = None  # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs\n    max_det = 1000  # maximum number of detections per image\n    amp = False  # Automatic Mixed Precision (AMP) inference\n\n    def __init__(self, model, verbose=True):\n        \"\"\"Initializes YOLOv5 model for inference, setting up attributes and preparing model for evaluation.\"\"\"\n        super().__init__()\n        if verbose:\n            LOGGER.info(\"Adding AutoShape... \")","sourceCodeStart":822,"sourceCodeEnd":858,"githubUrl":"https://github.com/ultralytics/yolov5/blob/20d1d78a08277e365d57bfa3a2cce752772d9e59/models/common.py#L822-L858","documentation":"_request_ssrf_url raises ValueError after exceeding max_redirects (default 5) HTTP redirects, each hop having passed the SSRF check. The loop performs at most max_redirects+1 GETs with allow_redirects=False; if every response is still a redirect, the chain is declared too long or looping. Typical causes are a URL-shortener chain, a misconfigured server with a redirect loop (http<->https or trailing-slash ping-pong), or a host that always redirects (e.g. auth walls).","triggerScenarios":"attempt_download on a link behind several shorteners/proxies totalling more than 5 hops; a server whose Location header redirects back to itself; CDN auth redirects that never terminate for unauthenticated clients.","commonSituations":"Mirrors behind corporate proxies that add redirect hops; misconfigured object storage (S3/MinIO) website endpoints; using bit.ly-style URLs for weights.","solutions":["Resolve the final URL with curl -sIL <url> | grep -i location and use that direct URL.","Pass a higher budget explicitly: _request_ssrf_url(url, max_redirects=10) if the chain is legitimately long.","Fix the server-side redirect loop (trailing slash, http->https both ways).","Download the file manually and pass the local path."],"exampleFix":"# before\nbuf = _request_ssrf_url('https://bit.ly/yolov5s-redirect-chain')\n\n# after\nbuf = _request_ssrf_url('https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s.pt')","handlingStrategy":"retry","validationCode":"import requests\n\ndef resolves_within(url: str, max_redirects: int = 5) -> bool:\n    s = requests.Session()\n    try:\n        for _ in range(max_redirects + 1):\n            r = s.get(url, stream=True, allow_redirects=False, timeout=10)\n            if not r.is_redirect:\n                r.close()\n                return True\n            url = r.headers.get('location', '')\n            r.close()\n    except requests.RequestException:\n        return False\n    return False","typeGuard":null,"tryCatchPattern":"try:\n    resp = _request_ssrf_url(url)\nexcept ValueError as e:\n    if 'Too many redirects' in str(e):\n        resp = _request_ssrf_url(url, max_redirects=10)  # retry with larger budget","preventionTips":["Use final/direct artifact URLs instead of shorteners in configs.","Pre-resolve redirect chains once with curl -IL during pipeline setup."],"tags":["network","redirects","download","http"],"backgroundTag":null,"analyzedSha":"20d1d78a08277e365d57bfa3a2cce752772d9e59","analyzedAt":"2026-08-15T02:56:15.443Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}