>_ IzzyLab

Hands-on task

This task is step 15 of the course “nginx basics”

Redirect HTTP to HTTPS

medium~10 min

TLS is already configured: nginx serves HTTPS on 443 (self-signed certificate). Now make nginx on port 80 answer everyone with a 301 redirect to the https:// version of the same address — so nobody uses plain HTTP.

What you'll practise:
  • nginx
  • 301 redirect
  • return
  • server block
  • https

Topic breakdown

The classic "force HTTPS" pattern: plain HTTP on port 80 should serve nothing of substance — it merely tells the browser "the same thing, but over https". Technically this is a 301 Moved Permanently status with a Location header pointing at the target address. In nginx each listening port is a separate server { ... } block, so the working HTTPS block on 443 doesn't need to be touched: a separate block on port 80 is added alongside it. For the redirect to work for any host and path, rather than one hardcoded domain, the target URL is built from nginx's built-in variables (the requested host and the original URI). After the edit, the config is checked with nginx -t and reloaded.

What's checked

  1. port 80 answers with a 301 redirect
  2. Location leads to https:// of the same host, path and query
  3. HTTPS still serves the page

What it looks like