Redirecting with Nginx

Common Redirects used in Nginx

Some Common Usages

Here are some common redirects that you may need to implement with Nginx

Redirect From www.domain1.com to www.domain2.com

server {

    server_name www.domain1.com;

    rewrite ^/$ http://www.domain2.com redirect; // redirect = temporary
    rewrite ^/$ http://www.domain2.com permanent; // redirect = permanent
}

Redirect url on old domain to new domain

server {
   server_name www.olddomain.com;

    rewrite ^/oldlocation$ http://www.newdomain.com/newlocation redirect; // redirect = temp
    rewrite ^/another-location$ http://www.newdomain.com/another-location permanent; // redirect = perm
}

Switch HTTP to HTTPS

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

    // other possible return types are 301, 302, 303, 307
}