Nginx Crumbs - Rewrite vs Return

More often than not there are times when your initial thought process changes mid way through your production ready application and you decide to change your application url. It could be your scheme (from a non-www to a www or vice-versa) or it could be your protocol (say, from http to https).
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

  • Only the part of the original url that matches the regex is rewritten.
  • Slower than a Return.
  • Returns HTTP 302 (Moved Temporarily) in all cases, irrespective of permanent.
  • Suitable for temporary url changes.
RETURN
  • The entire url is rewritten to the url specified.
  • Faster response than rewrite.
  • Returns HTTP 301 (Moved Permanently).
  • Suitable for permanent changes to the url.
  • No need to set permanent.

More details on nginx can be found here

Comments

Popular posts from this blog

To DR or Not To DR

High Availability NAT for AWS VPC with Multiple Private Subnets.

Load Balancer with SSL offloading - nginx + HAProxy