Nginx - Rewrite vs Redirect

More often than not there are times when the initial thought process around a product changes mid way through development and one might need to change the application URL. There are two ways of implementing this change in nginx.

Redirect from non-www to www

server {
    server_name example.com;
    # Option 1
    return 301 $scheme://$host$request_uri;
    # Option 2
    rewrite ^ http://$host$request_uri? permanent;
}

Redirect from http to https

server {
    server_name example.com;
    # Option 1
    return 301 https://$server_name$request_uri;
    # Option 2
    rewrite ^ https://$server_name$request_uri? permanent;
}

REWRITE

  1. Only the part of the original URL that matches the regex is rewritten.
  2. Slower than a Return.
  3. Returns HTTP 302 (Moved Temporarily) in all cases, irrespective of permanent.
  4. Suitable for temporary URL changes.

RETURN

  1. The entire URL is rewritten to the URL specified.
  2. Faster response than rewrite.
  3. Returns HTTP 301 (Moved Permanently).
  4. Suitable for permanent changes to the URL.
  5. No need to set permanent.

More details on nginx can be found here