Course lectures : 1 of 1

Nginx 301 / 302 redirect

Last updated: 14th December 2015

nginx301 redirect302 redirectnginx redirect

Nginx 301 / 302 redirect

Today we will have a look at how to set up a 301 (permanent) or 302 (temporary) redirect on Nginx server.

We will need sudo privileges so make sure that you have either root or sudo user credentials when connecting via ssh.

To do a redirect on a given domain, first navigate to /etc/nginx/sites-available

cd /etc/nginx/sites-available

Within this directory you'll find the config file for the domain we wish to apply the redirect to - say that our domain is and we wish to redirect it to

We need to either open the file called with sudo privileges and edit its content or remove it and create a new one (also with sudo privileges). I'm going to go with the later as it saves me time removing lines of code.

sudo rm -rf

You might be prompted for a password - type it and hit Return on your keyboard. File has been removed - now let's create a new one:

sudo nano

Inside of this file we need to create a server block with 3 options:

server {
    listen 80;
    return 301 $scheme://$request_uri;

The listen 80 line listens for any requests that come via port 80. server_name declares the domain that we are interested in - this usually corresponds to the name of the file that contains these settings. The last line returns the 301 (you can change it to 302 if you only want a temporary redirect). The $scheme variable returns whatever scheme was used to request the domain so that we can use the same one for the redirect, appending the two forward slashes, domain we want to redirect the request to, followed by the $request_uri, which contains whatever the original request had after the domain name.

With all this done - don't forget to restart nginx:

sudo service nginx restart


If you'd like to include code example please wrap your code within <pre><code> tags.

function fullName(firstName, lastName)
    return firstName + ' ' + lastName;