>_ IzzyLab

Hands-on task

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

Redirect www to non-www

medium~12 min

Configure nginx (port 80): requests with the host www.example.com must get a 301 redirect to http://example.com (the same path). Requests to example.com are served as usual.

What you'll practise:
  • nginx
  • server_name
  • return
  • 301 redirect
  • $request_uri

Topic breakdown

Domain canonicalization is bringing all address variants (with www, without it) to one main one, so search engines don't treat them as different sites; for a permanent move, code 301 is used. In nginx, requests are routed among server blocks based on the server_name directive, matched against the Host header. An instant redirect without touching files is done by the return directive with a code and a target URL, and to preserve the original path and query string, the $request_uri variable is substituted into the target. In tests the Host header is overridden with the curl -H flag, which lets you pick the right block without real DNS.

What's checked

  1. www returns a 301 redirect
  2. Location leads to http://example.com
  3. the path and query are kept in the redirect
  4. example.com is served as usual

What it looks like