Sub topic 8
Redirecting: 301 versus 302
This chapter covers the redirect step of a URL shortener: what the server sends back when someone opens a short link, and why the choice between a 301 and a 302 status code affects caching, analytics, and your ability to change links later. It assumes you know basic HTTP (methods, status codes, headers) and have read the earlier chapters on API design and the data model. The caching chapter that follows builds on the decisions made here.
What a redirect response looks like
When a browser requests GET /aZ3k9Qx, the service looks up the long URL and answers with a redirect. A redirect has two parts: a 3xx status code and a Location header holding the destination. The response body is usually empty or a short fallback message. The browser reads Location and sends a second request to that address.
HTTP/1.1 302 Found
Location: https://example.com/articles/2026/very-long-path?ref=newsletter
Cache-Control: private, max-age=0
Content-Length: 0The short link service never serves the destination page. It only points to it. This keeps the read path small: one lookup, one tiny response.
The candidates: 301, 302, 307, 308
Four status codes are relevant. They differ on two questions. Is the redirect permanent or temporary? Does the client keep the original HTTP method when it follows the redirect?
| Status | Name | Meaning | Method on follow-up request |
|---|---|---|---|
| 301 | Moved Permanently | The resource has a new permanent address. | Clients may change POST to GET. |
| 302 | Found | The resource is temporarily elsewhere. | Clients may change POST to GET. |
| 307 | Temporary Redirect | Temporary, same as 302 in meaning. | Method must stay the same. |
| 308 | Permanent Redirect | Permanent, same as 301 in meaning. | Method must stay the same. |
For a URL shortener, users open short links by clicking or pasting them, which produces GET requests. Method preservation rarely matters here, so the real decision is permanent versus temporary. Most services pick 301 or 302. Use 307 or 308 only if clients might send non-GET requests to short links, for example a webhook URL that has been shortened.
What "permanent" means for caching
The difference between 301 and 302 is mostly about caching behavior.
- A 301 response is cacheable by default. A browser that receives one may store the mapping from short URL to long URL and skip your server on later visits. Intermediate caches such as corporate proxies and CDNs may do the same.
- A 302 response is not cached by default unless you add explicit
Cache-ControlorExpiresheaders. The browser asks your server every time.
Search engines also treat the codes differently. A 301 tells a crawler that the destination is the canonical address, so ranking signals are generally passed to it. A 302 tells the crawler the short URL is the stable address and the destination is temporary. For a shortener, this matters little for users, but it affects how search engines index your short domain.
Trade-offs between the two
Server load and latency
With 301, repeat visitors from the same browser never reach your servers. That cuts read traffic and makes repeat visits faster, because the browser skips a network round trip. With 302, every click hits your service, so your capacity estimate from the earlier chapter applies in full. The load reduction from 301 only helps repeat visits by the same client, so for links that each person clicks once, the saving is small.
Analytics
If you want to count clicks, 302 is the safer choice. A cached 301 means some clicks never reach you, so your counts are too low and you cannot tell by how much. The chapter on click analytics depends on every click being visible to the server.
Changing or removing links
A cached 301 is hard to undo. Suppose a user edits a link's destination, the link expires, or you disable it because it points to malware. Browsers that cached the 301 keep sending visitors to the old destination, and you cannot reach into their cache to fix it. Browsers may keep a 301 for a very long time, and the HTTP specification does not give you a way to revoke it. Expiry (covered in the custom aliases chapter) and abuse takedowns both need the server to stay in control, which favors 302.
Summary of the decision
| Concern | 301 | 302 |
|---|---|---|
| Repeat-visit load on your servers | Lower | Full |
| Click counts accurate | No, cached visits are invisible | Yes |
| Edit, expire, or block a link quickly | Hard | Easy |
| Search engine treatment | Destination treated as canonical | Short URL treated as stable |
A common default is 302 for any product with analytics, editable links, or expiry. Choose 301 when links are immutable, you do not report click counts, and reducing load matters.
A middle path: 301 with limited caching
You can send a 301 and still limit how long it is cached by adding a Cache-Control header. Browsers honor max-age on a 301, so you can bound the staleness.
HTTP/1.1 301 Moved Permanently
Location: https://example.com/articles/2026/very-long-path
Cache-Control: public, max-age=3600Now a browser reuses the redirect for an hour and then asks again. Your analytics lose up to an hour of repeat clicks per browser, and a takedown reaches most users within an hour. This is a compromise, not a fix. Some clients ignore the header on a 301 and treat it as permanent, so a 302 with an explicit Cache-Control header is usually more predictable. Test with the browsers you care about.
The reverse also works. A 302 with Cache-Control: public, max-age=60 lets a CDN absorb bursts for a viral link, while still giving you a one-minute window to change the mapping.
Implementing the redirect handler
The handler combines the cache-aside lookup from the previous design with the status code decision. This example uses Flask. It assumes a resolve function with the cache-aside logic and an expires_at check handled elsewhere.
from flask import Flask, redirect, abort
app = Flask(__name__)
REDIRECT_STATUS = 302 # change to 301 only if links are immutable and uncounted
def resolve(short_code: str):
# Replace with the cache-aside lookup (cache, then database).
table = {"aZ3k9Qx": "https://example.com/articles/2026/very-long-path"}
return table.get(short_code)
@app.get("/<short_code>")
def follow(short_code: str):
long_url = resolve(short_code)
if long_url is None:
abort(404)
response = redirect(long_url, code=REDIRECT_STATUS)
response.headers["Cache-Control"] = "private, max-age=0"
return response
if __name__ == "__main__":
app.run(port=8000)Run it, then check the headers with curl -i http://localhost:8000/aZ3k9Qx. You should see 302 FOUND and a Location header. Requesting an unknown code returns 404.
Edge cases and common errors
- Unknown, expired, or disabled codes. Return 404 for codes that never existed. For expired links, 410 Gone is more accurate and tells clients not to retry. Never return a redirect for them. Make sure these error responses are not cached for long, or a code that is later created or restored will keep failing.
- Caching a 404 or 410 aggressively. A CDN that caches a "not found" for a code can break a link that is created a moment later. Use short lifetimes for error responses.
- Malformed destinations. Store only validated absolute
httporhttpsURLs. ALocationvalue such asjavascript:or one containing newline characters can create security problems, including header injection. Validate on creation and let the framework encode the header. - Open redirect abuse. A shortener is by design an open redirect. Attackers use it to hide phishing destinations behind a trusted domain. The abuse chapter covers mitigations such as scanning destinations and showing interstitial warning pages.
- Switching from 301 to 302 later. Browsers that already cached 301 responses will not notice the change. Pick the code before launch. Moving from 302 to 301 later is safe, but moving the other way does not reach cached clients.
- Redirect chains. If a destination is itself a short link, the browser follows several hops. Browsers cap the number of redirects, and each hop adds latency. Consider rejecting links that point to your own domain.
- Using 303 or 307 by accident. Frameworks sometimes default to 303 or 307 for helpers. Check the actual status code on the wire with
curl -i, not just the framework's documentation.
Exercises
Exercise
A shortener lets users edit a link's destination and shows a click count on each link's dashboard. Which status code should it use by default, and what are two specific problems if it used a plain 301 instead?
Show answer
Use 302. With a plain 301, browsers cache the mapping, so (1) repeat clicks from the same browser never reach the server and the click count is too low, and (2) after a user edits the destination, browsers that cached the old redirect keep sending visitors to the old URL, and the service cannot invalidate that cache.
Exercise
You want a CDN to absorb traffic spikes for a viral link, but you also want any change to the destination to take effect within about one minute. What response would you send, and why is it more predictable than a 301 with a short max-age?
Show answer
Send a 302 with Cache-Control: public, max-age=60. The CDN reuses the response for up to 60 seconds, then fetches a fresh one, so changes appear within about a minute. It is more predictable than a 301 with a short max-age because some clients treat a 301 as permanent and ignore or override the max-age value, while a 302 is temporary by definition and its caching follows the header you set.