HTTP Redirects: 301, 302, 303, 307 and 308 Explained
Diagnose POST turning into GET after redirects. Compare 301, 302, 303, 307 and 308 with curl, body-preservation checks and a runnable local HTTP lab.
A redirect is a response that can cause a new request; the new request is not necessarily a replay of the first. For automatic redirects, 307 and 308 preserve the request method. A 303 points to a retrieval response, while 301 and 302 permit historical POST-to-GET behavior. Diagnose the actual method and body at every hop, then choose a status and client policy that match the operation.
Investigate the second request, not just the final status
An API call starts as POST with a payload, returns a redirect, and eventually ends at 200 OK. Yet the handler reports that no data arrived. The final status describes the last response; it does not prove that the original method, body or destination survived the chain. Start by treating the redirect as a boundary between two requests.
Common triggers include a trailing-slash rule, an HTTP-to-HTTPS entry point, an authentication gateway or a moved API route. The first service may redirect before application code runs, so the application log alone can hide the important response. Record which component generated each Location header before modifying the final handler.
This guide separates protocol meaning from observed client behavior. The reproducible example uses curl 8.5.0 and a Python 3.12.14 HTTP/1.1 server on IPv4 loopback. It checks real requests received by the server, including their bodies. It does not claim browser, reverse-proxy, TLS or cross-origin conformance from those local results.
Choose redirect meaning and method handling separately
The permanent or temporary distinction answers where future references should point. Method handling answers what a client sends when it follows this response. These decisions are related but independent: a temporary API relocation may still need POST preserved, while a completed form action may intentionally lead to a different GET resource.
RFC 9110 allows user agents to change POST to GET after 301 or 302. It does not require every client to make that change. A 303 directs the client toward a retrieval, normally GET, with HEAD also relevant for a HEAD request. Automatic redirection with 307 or 308 must retain the method. A client can also decline to follow.
Do not replace an intentional 303 success flow with 307 merely because the original request was POST. If the server has already performed the action and offers a separate receipt page, retrieval is the desired next step. Conversely, a route forwarding an unprocessed submission needs a different policy from a receipt link.
| Status | Routing meaning | Method consideration |
|---|---|---|
| 301 Moved Permanently | Permanent new URI | POST may become GET; do not assume replay |
| 302 Found | Temporary different URI | POST may become GET; client policy matters |
| 303 See Other | Retrieve a different resource as a response | Use retrieval rather than repeating the action |
| 307 Temporary Redirect | Temporary different URI | Automatic follow must preserve the method |
| 308 Permanent Redirect | Permanent new URI | Automatic follow preserves the method |
Source: RFC 9110: HTTP semantics and redirection status codes ↗
What curl actually sent in the local fixture
With --location and --data-binary, the data option selects POST without needing --request POST. In the tested version, 301, 302 and 303 produced a follow-up GET with an empty body. Both 307 and 308 produced a follow-up POST with the original bytes. All five GET cases remained GET.
The comparison is deliberately small: one same-origin relative Location, a short replayable ASCII payload, no credentials and no application mutation. A matching method and body in this fixture establishes those properties for this client invocation. It does not establish that an uploaded stream can rewind, that a destination accepts the content, or that repeating a business operation is harmless.
For a manual diagnosis, first inspect the initial response without following it. Then enable following with a finite redirect limit and compare the request lines and payload lengths. Use invented data while examining traces. A verbose trace can expose sensitive headers; record only the fields needed to explain the failure.
# Use a controlled test endpoint that accepts this invented payload.
# Without --location, inspect the first response.
curl --max-time 10 --include --data-binary 'demo=redirect&value=10' \
'https://api.example.test/old-endpoint'
# Then inspect every response header while following a bounded chain.
curl --max-time 10 --location --max-redirs 3 --dump-header - \
--data-binary 'demo=redirect&value=10' \
'https://api.example.test/old-endpoint'
# example.test is a placeholder: replace it with your controlled endpoint.Source: curl manual: --location, --request, redirect limits and POST options ↗
Why adding -X POST can make the trace misleading
The --request option sets the method string. It is not a general instruction to preserve every aspect of a request across redirects. In the tested --location case, adding --request POST to a data-bearing request through 302 made the next request say POST, but the next request body was empty. Looking only for the word POST would miss the problem.
The dedicated --post301, --post302 and --post303 options changed the corresponding curl cases to retain POST and the payload in this fixture. That is an explicit client override, not evidence that a redirect response requires such behavior. In particular, overriding a 303 can defeat a deliberate post-action retrieval flow. Prefer correcting the route contract before applying an override.
Keep the exact command and client version with the incident notes. A library wrapper, different flags or a later client feature can select a different policy. This guide tests --location, not every redirect feature in current curl. If a SDK works while a shell reproduction fails, compare their policies before concluding that one server response is inconsistent.
Source: curl manual: --location, --request, redirect limits and POST options ↗
Run the complete 18-check loopback lab
Save the following as redirect_lab.py and run it with Python 3 and curl installed. It chooses an unused loopback port, starts its own temporary server and shuts it down in finally. It does not contact a public API or write application data. The fixture uses --noproxy for loopback and places -q first to avoid loading a personal curl configuration.
The script checks five POST cases, five GET cases, three explicit POST overrides, the custom-method trap, following disabled, a two-hop chain, HEAD and a bounded redirect loop. Each successful comparison includes the requests observed by the server rather than inferring behavior from response text alone. The POST matrix also verifies the final echoed method and body.
The tested run passed 18 checks across 37 real local HTTP requests. In the chain case, the first 307 preserved POST and the second 303 switched to GET. The loop case allowed two followed redirects, then stopped with curl exit code 47 after three requests. These results demonstrate why both per-hop inspection and a finite limit belong in a reproduction.
import json
import subprocess
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
payload = b'demo=redirect&value=10'
events = []
checks = 0
request_count = 0
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def handle_request(self):
global request_count
request_count += 1
self.connection.settimeout(3)
body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
events.append((self.path, self.command, body))
location = None
status = 200
if self.path.startswith('/r/'):
status = int(self.path.rsplit('/', 1)[1])
location = '/echo'
elif self.path == '/loop':
status, location = 302, '/loop'
elif self.path == '/chain':
status, location = 307, '/r/303'
content = json.dumps({'method': self.command,
'body': body.decode('ascii')}).encode()
self.send_response(status)
if location:
self.send_header('Location', location)
self.send_header('Content-Type', 'application/json')
self.send_header('Cache-Control', 'no-store')
self.send_header('Content-Length', str(len(content)))
self.send_header('Connection', 'close')
self.end_headers()
if self.command != 'HEAD':
self.wfile.write(content)
do_GET = do_POST = do_HEAD = handle_request
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
server.daemon_threads = True
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = f'http://127.0.0.1:{server.server_port}'
def run(path, options):
events.clear()
return subprocess.run(
['curl', '-q', '--noproxy', '127.0.0.1', '--http1.1',
'--silent', '--show-error', '--connect-timeout', '2',
'--max-time', '5', '--max-redirs', '3',
*options, base + path],
capture_output=True, timeout=7, check=False)
def verify(condition, name):
global checks
if not condition:
raise AssertionError((name, events))
checks += 1
try:
for status in [301, 302, 303, 307, 308]:
result = run(f'/r/{status}', ['--location', '--data-binary', payload.decode()])
method = 'GET' if status in [301, 302, 303] else 'POST'
body = b'' if method == 'GET' else payload
verify(result.returncode == 0 and events == [
(f'/r/{status}', 'POST', payload), ('/echo', method, body)
] and json.loads(result.stdout) == {'method': method, 'body': body.decode()},
f'POST through {status}')
for status in [301, 302, 303, 307, 308]:
result = run(f'/r/{status}', ['--location'])
verify(result.returncode == 0 and events == [
(f'/r/{status}', 'GET', b''), ('/echo', 'GET', b'')
], f'GET through {status}')
for status in [301, 302, 303]:
result = run(f'/r/{status}', ['--location', f'--post{status}',
'--data-binary', payload.decode()])
verify(result.returncode == 0 and events == [
(f'/r/{status}', 'POST', payload), ('/echo', 'POST', payload)
], f'explicit --post{status}')
result = run('/r/302', ['--location', '--request', 'POST',
'--data-binary', payload.decode()])
verify(result.returncode == 0 and events == [
('/r/302', 'POST', payload), ('/echo', 'POST', b'')
], 'custom method is not a body-preservation switch')
result = run('/r/302', ['--data-binary', payload.decode()])
verify(result.returncode == 0 and events == [('/r/302', 'POST', payload)],
'no --location means no follow-up request')
result = run('/chain', ['--location', '--data-binary', payload.decode()])
verify(result.returncode == 0 and events == [
('/chain', 'POST', payload), ('/r/303', 'POST', payload), ('/echo', 'GET', b'')
], '307 then 303 changes method at the second hop')
result = run('/r/303', ['--location', '--head'])
verify(result.returncode == 0 and events == [
('/r/303', 'HEAD', b''), ('/echo', 'HEAD', b'')
], 'HEAD remains HEAD with --head')
result = run('/loop', ['--location', '--max-redirs', '2'])
verify(result.returncode == 47 and events == [('/loop', 'GET', b'')] * 3,
'two followed redirects stop a loop with curl exit 47')
print(f'PASS: {checks} checks; {request_count} HTTP requests; local HTTP/1.1 only')
print(subprocess.check_output(['curl', '--version'], text=True).splitlines()[0])
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
Turn the evidence into a targeted repair
First, write down the intended operation: forward an unprocessed command, show a receipt, or move a resource permanently. Identify whether the initial endpoint already applied a side effect. If that fact is unclear, use server-side request identifiers and application logs to establish it before allowing another submission. A redirect is not an idempotency mechanism.
Second, map the chain as observed: original URL and method, response status, Location, next URL and method, and next body length or a digest of invented test data. Resolve relative locations against the response URL. A chain can preserve the body at one hop and drop it at another, so checking only the first redirect is incomplete.
Third, repair the component responsible for the mismatch. A canonical API URL in the client can avoid a needless hop. A forwarding rule may need 307 or 308. A completed form workflow may need to keep 303 and fix the client expectation instead. Do not change all redirects globally: page navigation, login and API submission can require different behavior.
Finally, repeat through the actual gateway and protocol configuration, checking the final operation as well as transport details. Compare with the local fixture to locate the difference. If the request reaches the intended handler with correct bytes but still fails, move on to content parsing, validation or authorization rather than continuing to change redirect codes.
Keep replay, credentials and caching in the investigation
Method preservation does not make a request safe to repeat. A payment, job submission or other action can run more than once if the application and client do not coordinate retries and idempotency. For an upload, also verify that the body source can be replayed. The in-memory payload in this lab avoids that problem and therefore cannot test it.
Cross-origin redirects add a separate destination and credential policy. Do not assume that authentication headers, cookies or browser access behave like a same-origin loopback request. Do not enable --location-trusted as a generic fix for a missing header; the curl manual explains that it can forward credentials and other secrets beyond the initial host. Review the destination and client rules first.
A permanent redirect can also remain visible through caching after a server rule changes. The fixture explicitly sends Cache-Control: no-store and has no intermediary, so it does not reproduce that situation. Check the actual response controls and caches when a corrected deployment still appears to redirect. Clearing one browser does not establish what every client or shared cache now sees.
The useful outcome is a documented request path whose method, bytes and effect match the intended operation. Keep the smallest reproduction and its observed chain alongside the fix. That gives a future maintainer enough evidence to distinguish an intentional retrieval redirect from a lost submission, without relying on a final success status as proof.
Your next steps
- Choose permanent versus temporary routing separately from method-preservation requirements. Use 303 for an intentional retrieval after an action; use 307 or 308 when the redirected operation must retain its method.
- Compare the original request and every follow-up request. A final 200, or a POST word in a trace, does not prove the original body reached the intended endpoint.
- Reproduce with a bounded local fixture and the actual client version. Confirm replay safety, destination policy and behavior through the real deployment path before changing production redirects.
Sources & official resources
Linked resources checked on 2026-10-30. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →