Course outline · 0% complete

0/25 lessons0%

Course overview →

Redirects: when the answer is "look elsewhere"

lesson 5-4 · ~10 min · 17/25

Following the moved sign

URLs outlive their content: pages get renamed, sites move to new domains, and every http:// request should become https://. Without a forwarding mechanism, each of those changes would break every existing link, bookmark, and search result. The mechanism is the redirect, and you met its status class in lesson 4-3: 3xx, "look elsewhere".

A redirect response carries no useful body. Its payload is one header, Location, holding the URL to try instead:

HTTP/1.1 301 Moved Permanently
Location: https://example.com/

The client is expected to issue a new request to that URL. Browsers do this automatically and silently — you only notice the address bar change. The two codes to know:

  • 301 Moved Permanently: the move is forever. Browsers and caches remember it, and search engines transfer the page's ranking to the new URL.
  • 302 Found: a temporary detour ("after login, go back to /inbox"). Nothing should remember it.

Redirects are an everyday engineering tool — http→https upgrades, old paths kept alive after a rename, short links — but each one costs a full round trip (lesson 3-4), so chains of them are a known page-speed smell.

Watch redirects happen in curl. Unlike a browser, curl does NOT follow them by default, which makes it perfect for seeing the machinery.

Step 1/3: Request the http:// version of a site. The server does not serve the page — it answers 301 and points at the https URL in the Location header. Note the empty-ish body: the real content lives at the destination.

$ 

Code exercise · bash

Your turn, be the browser. The lookup function plays a set of servers: given a URL it echoes that URL's Location header, or nothing if the URL serves real content. Follow the trail with a while loop: while lookup returns something non-empty, print the hop, move to it, and count it. [ -n "$x" ] tests that a string is non-empty.

Quiz

You are permanently moving your blog from blog.old.com to blog.new.com. Which status code should the old server answer with, and why does the choice matter?

Problem

A script fetches an API URL with plain curl and gets an empty body and status 302. Which response header holds the address the script should retry, and which curl flag makes curl follow it automatically? Answer as: header, flag.