How to Setup a NGINX 301 Redirect

coding on a laptop

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

NGINX is a very powerful web server tool for balancing the needs of software or a web application. It’s used by almost 42.2% of all known websites and known web servers, falling just barely behind Apache, which is used by 43.3% of all websites as of 2019. Needless to say, it’s a popular and user-friendly open source software.

NGINX 301 Redirects are a very useful way to properly redirect addresses within a browser. Website owners will typically need to do this when changing domains or rearranging content on their website.

So how exactly is this redirect performed? Let’s dive into how one can perform an NGINX 301 Redirect step by step.

Related: The Ultimate Beginners Guide to Showing Up On The First Page of Google

What is an NGINX 301 Redirect?

NGINX is a type of open source software for caching, load balancing, reverse proxying, and much more. Originally, NGINX was designed as a web server for improving performance and stability. Outside of NGINX’s HTTP server abilities, it can also be used as a proxy server for email as well as a reverse proxy and load balancer for various types of servers.

NGINX 301 Redirect is a form of HTTP redirection. One can utilize HTTP redirection to direct one domain or address to another domain or address. There are several types of redirects, all of which have different meanings in the client browser. The two most used and well-known types of redirect are “temporary” redirects and “permanent” redirects.

Permanent redirects such as NGINX 301 Redirect simply makes the browser forget the old address entirely and prevents it from attempting to access that address anymore. These redirects are very useful if your content has been permanently moved to a new location, like when you change domain names or servers.

Now that we know what an NGINX 301 Redirect is, let’s cover the different ways of setting one up.

Join Over 1000 Other Companies and Get Your Website Analyzed By Twiz

18567
18568
18569
18562
18564

How to Set Up an NGINX 301 Redirect

If you need to set up an NGINX redirect, there are several options you can choose from.

The easiest and quickest way to perform a redirect is with the “return” statement. To perform this statement, place the following code in your server block:

return 301 https://sample.com$request_uri;

This redirect is permanent and ideal for permanent content migration after a domain change. The complete sample server block sound looks something like this:

server {
    listen 80;
    listen [::]:80;
    hostname sample.com www.sample.com;
    return 301 https://sample.com$request_uri;
}

There are also more complex ways to perform this redirect. You could also use a regexp statement such as the following:

rewrite ^/foo/(bar)/(.*)$ https://$server_name/$1/$2 permanent;

This is still quite a fast NGINX statement outside of return. If you would prefer a temporary redirect (which would be a NGINX 301 Redirect or HTTP 302 redirect) you can simply use “redirect” instead of “permanent.” An example of this is as follows:

server {
    listen 80;
    listen [::]:80;
    hostname sample.com www.sample.com;
    root /var/www/sample.com/public;
    rewrite ^/foo/(bar)/(.*)$ $scheme://$server_name/$1/$2 permanent;
}

Join Over 1000 Other Companies and Get Your Website Analyzed By Twiz

18567
18568
18569
18562
18564

Pretty easy, right? Now, if you have a group of addresses or regular expressions that need to all be redirected separately and differently, you can use maps. Maps can be defined in separate files and their definitions must be outside of the server block. It would look something like this:

include redirect-map.conf;
server {
    […]
    if ( $redirect_uri ) {
        return 301 $redirect_uri;
    }
}

Once executed, the configuration file for the redirect map would look similar to this example:

map $request_uri $redirect_uri {
    /about.html          /about-us;
    /partners.html      /our-partners;
    /services.html       /our-services;
}

It’s worth noting that regular expressions are sensitive to case matching. Case-sensitive matching should start with ~ and case-insensitive matching should start with ~*. Note that $redirect_uri can be named whatever you wish, but the variable name within the map must be the same as the server block. This example code shows this:

map $request_uri $redirect_uri {
    /about.html          /about-us;
    /partners.html      /our-partners;
    /services.html       /our-services;
    # Match any url that ends in services.html or services.htm
    ~services\.html?$    /our-services;
    # case-insensitive version of the above
    ~*services\.html?$   /our-services;
    # A named capture that maps
    # e.g. service-1234.html into /services/item-1234/overview
    ~service-(?<sku>\d+)\.html   /services/item-$sku/overview;
}

There are also additional variables you can consider that are already predefined in NGINX to be used in configurations. These include:

  • $server_name. This is the first name from the hostname declaration in one’s configurations for the server block that immediately responds to the request.
  • $request_uri. This is the complete original request Uniform Resource Identifier (or URI) that includes arguments.
  • $request_filename. This is the file path for the present request.
  • $scheme. This is the specific scheme used for your present request, such as “https.”
  • $host. This is the hostname supplied by the client for the present request.

There are also dozens of other variables that could be useful for your redirects.

There are probably a million different uses for redirects in NGINX. Some of them include:

Join Over 1000 Other Companies and Get Your Website Analyzed By Twiz

18567
18568
18569
18562
18564

Create generic redirects

Some server blocks cover more than one website, such as a multisite network. If you do not want all of those websites to redirect to the exact same hostname, you can perform a www/non-www redirect. It’s worth noting that using separate server blocks is the most efficient option.

To perform a non-www to www redirect the code would look something like this:

if ( $host !~ ^www\. ) {
    return 301 $scheme://www.$host$request_uri;
}

Just as well, you can perform a www to non-www redirect:

if ( $host ~ ^www\.(?<domain>.+)$ ) {
    return 301 $scheme://$domain$request_uri;
}

HTTP to HTTPS

You can perform this redirect by using;

return 301 https://$host$request_uri;

Create a canon hostname

This redirect is useful for avoiding duplicated content. The code would look something like this:

server_name sample.com www.sample.com sample.net www.sample.net _;
if ( $host != $server_name ) {
    return 301 $scheme://$server_name$request_uri;
}

How was our guide to performing an NGINX 301 Redirect? Tell us what you think, along with your own tips for executing this redirect, in the comments below.

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Marketing

Inside Sales vs. Outside Sales: Best Advice from Industry Pros

Sales are a critical component of most businesses that largely determine whether or not they will succeed within the overall market, especially against other competing enterprises operating within the same industry. However, it’s essential to understand that businesses can utilize many different types of sales, and each comes with a wide range of various benefits

Marketing

Sales Analysis Tips & Techniques: Hit Your KPIs

If you want to hit your sales goals each and every month, guesswork and intuition aren’t going to cut it. You need data and lots of it. Sales data analysis relies on your CRM to capture all of the information about the deals closed by your sales reps. Conducting sales analysis regularly is the most

Do You Want To Boost Your Business?

Let's hop on a call, and we'll provide you a plan

Looking to Grow Your Website?

FREE

Download free eBook with advice from our experts

No Thanks, I Do Not Want to Grow

Join the Twiz Growth Newsletter

Learn how to scale your business to become an industry leader through digital marketing.

FREE

No thanks, I don't want to learn
Scroll to Top