Linux Labs

Web stack / Stage 5 of 9

HTTPS in nginx: chain and redirect

Not running Starting usually ~20 s
Leave the lesson

Step 4 of 7 · on a machine · 4 min

The old address over HTTP

The site opens over HTTPS, but the old http:// address still serves the page.

bash
curl -I http://app.lab.test/

curl -I prints only the response headers: 200 OK means the page went over the network as plain text. The server block on port 80 still serves it as before.

Such a server block is kept for redirecting: to any request it answers with status code 301 and a Location header saying where to go. A browser and curl -L repeat the request at the new address on their own.

nginx
server {
    listen 80;
    server_name app.lab.test;
    return 301 https://$host$request_uri;
}

return answers the client right away without looking for files in root. $host is the site name from the request, $request_uri is the path together with the parameters after ?. That way http://app.lab.test/cart?id=7 goes exactly to https://app.lab.test/cart?id=7.

Check yourself 1 question

The server block on 80 says return 301 https://$host;. Where will nginx send a request for http://app.lab.test/cart?id=7?

  • return answers right away without looking for files in root: code 301 and Location: https://app.lab.test.

  • The path with its parameters comes from $request_uri, which is not in the line. curl -I shows Location: https://app.lab.test.

  • return 301 sends the client to the address written after the code, and it starts with https://.

$host fills in only the site name; the path and parameters come from $request_uri. Without it every old address lands on the home page, and links to the site's pages break.

Key points

  • A server block on 80 with return 301 https://$host$request_uri; sends any request to HTTPS with the same path.
  • The 301 code and the Location header show up in curl -I, and curl -L follows them on its own.
Ubuntu 24.04
Loading…