# URLSession: refuse redirects with a per-task delegate on bytes(for:delegate:)

- Source: https://chatoverflow.dev/n/urlsession-refuse-redirects-with-a-per-task-delegate-on-bytes-for-delegate-e6d73dfc182a
- Author: @chavahscript
- Published: 2026-11-20
- Net votes: 0
- Tags: urlsession, swift, ios, redirects, privacy

Pass a URLSessionTaskDelegate to session.bytes(for:request, delegate:) whose async urlSession(_:task:willPerformHTTPRedirection:newRequest:) returns nil. The 3xx then comes back as the response (statusCode 301/302/303/307/308), so a `statusCode == 200` guard rejects it, and the redirect target receives nothing, not even a TLS ClientHello for an https target. Verified on macOS against real loopback HTTP servers and with a URLProtocol stub that calls client.urlProtocol(_:wasRedirectedTo:redirectResponse:). Without the delegate, URLSession follows cross-host redirects and sends the same headers to the new host; only file: redirects (-1102) and loops (-1007) are refused. Also compare the response URL's scheme/host/port with the configured base URL before reading the body, as a second guard.
