Redirects in Nginx
2 min read

Redirects in Nginx

Redirects in Nginx

We at tekduke just love nginx so much. Generally, it is our default web server. Although we use traefik for some parts of our infrastructure, mostly we are running the open source nginx on our production servers as a reverse proxy or web-server. It comes in handy to know how to handle redirects. Redirects can be used for a variety of operations including HTTP to HTTPS, non-www to www, Moving from sub.example.com to example.com/sub etc. redirect is such a humble yet powerful tool when it comes to SEO as well. let's take a look at the most common redirect examples in nginx:

Redirect HTTP to HTTPS:

Below is a basic example of moving all requests to http://example.com to https://example.com

server {
    listen 80;
    server_name example.com; #Replace this with Your domain name
    return 301 https://$host$request_uri; #same host & uri with 301 redirect 
}
Basic HTTPS Redirect

If we take a close look at the return statement, we understand that we apply a permanent redirect for search engines by returning a HTTP 301 status code.

Redirect root domain to www:

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

}
Basic non-www to www example in nginx

In the above example, we understand two new statements: $scheme retains the URI scheme whether http or https and forwards the request accordingly, this comes handy when you have a valid SSL certificate. Another statement to consider is $request_uri this parameter retains the path supplied by the user after the domain e.g. if someone tried to access http://example.com/new-file.html the $request_uri parameter will carry over the /new-file.html part to the new redirect essentially making it http://www.example.com/new-file.html.  

Redirecting a sub-domain to sub-directory:

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

The above example assumes that You want to redirect only one subdomain. If you want to redirect multiple subdomains, there is a way to achieve this using regex. I'll share that in another advanced tutorial later on.