ultralytics/yolov5 · error · ValueError

Too many redirects while fetching {url}

Error message

Too many redirects while fetching {url}

What it means

_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).

Source

Thrown at models/common.py:840

    except socket.gaierror as e:
        raise ValueError(f"Could not resolve hostname '{hostname}': {e}") from e
    for _family, _type, _proto, _canonname, sockaddr in results:
        addr = ipaddress.ip_address(sockaddr[0])
        if addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_reserved or addr.is_multicast:
            raise ValueError(f"Blocked request to internal address: {addr}")


def _request_ssrf_url(url: str, max_redirects: int = 5):
    """Fetch a URL after validating each resolved redirect target."""
    session = requests.Session()
    for _ in range(max_redirects + 1):
        _validate_ssrf_url(url)
        response = session.get(url, stream=True, allow_redirects=False)
        if not response.is_redirect:
            return response
        url = urljoin(response.url, response.headers["location"])
        response.close()
    raise ValueError(f"Too many redirects while fetching {url}")


class AutoShape(nn.Module):
    """AutoShape class for robust YOLOv5 inference with preprocessing, NMS, and support for various input formats."""

    conf = 0.25  # NMS confidence threshold
    iou = 0.45  # NMS IoU threshold
    agnostic = False  # NMS class-agnostic
    multi_label = False  # NMS multiple labels per box
    classes = None  # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
    max_det = 1000  # maximum number of detections per image
    amp = False  # Automatic Mixed Precision (AMP) inference

    def __init__(self, model, verbose=True):
        """Initializes YOLOv5 model for inference, setting up attributes and preparing model for evaluation."""
        super().__init__()
        if verbose:
            LOGGER.info("Adding AutoShape... ")

View on GitHub (pinned to 20d1d78a08)

Solutions

  1. Resolve the final URL with curl -sIL <url> | grep -i location and use that direct URL.
  2. Pass a higher budget explicitly: _request_ssrf_url(url, max_redirects=10) if the chain is legitimately long.
  3. Fix the server-side redirect loop (trailing slash, http->https both ways).
  4. Download the file manually and pass the local path.

Example fix

# before
buf = _request_ssrf_url('https://bit.ly/yolov5s-redirect-chain')

# after
buf = _request_ssrf_url('https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s.pt')
Defensive patterns

Strategy: retry

Validate before calling

import requests

def resolves_within(url: str, max_redirects: int = 5) -> bool:
    s = requests.Session()
    try:
        for _ in range(max_redirects + 1):
            r = s.get(url, stream=True, allow_redirects=False, timeout=10)
            if not r.is_redirect:
                r.close()
                return True
            url = r.headers.get('location', '')
            r.close()
    except requests.RequestException:
        return False
    return False

Try / catch

try:
    resp = _request_ssrf_url(url)
except ValueError as e:
    if 'Too many redirects' in str(e):
        resp = _request_ssrf_url(url, max_redirects=10)  # retry with larger budget

Prevention

When it happens

Trigger: 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.

Common situations: Mirrors behind corporate proxies that add redirect hops; misconfigured object storage (S3/MinIO) website endpoints; using bit.ly-style URLs for weights.

Related errors


AI-assisted analysis of ultralytics/yolov5@20d1d78a08 (2026-08-15). Data as JSON: /api/errors/6667c94eca6ad1f3. Report an issue: GitHub.