Beginner Fundamentals

Redirects

A redirect tells the browser to fetch a different URL. Nginx makes this simple with the return directive, which is fast and clear.

return 301 vs 302

The status code signals how permanent the redirect is:

  • 301: permanent. Browsers and search engines remember it.
  • 302: temporary. The change is expected to be undone later.
server {
    listen 80;
    server_name old-site.com;
    return 301 https://new-site.com$request_uri;
}

This permanently moves every request from old-site.com to new-site.com, keeping the path via $request_uri.

Redirecting a Single Path

You can redirect just one location:

location /old-page {
    return 301 /new-page;
}

Forcing the www or non-www Version

A common task is making one canonical hostname. Redirect www to the bare domain:

server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

Useful Variables

  • $host is the requested hostname.
  • $request_uri is the full path plus query string.
  • $scheme is http or https.

return vs rewrite

For simple “go to this URL” cases, return is preferred: it is explicit and efficient. Use rewrite only when you need pattern matching, covered in the next lesson.