Nginx: 301 permanently redirect a file or folder with nginx.conf

Last updated on

In Nginx, redirects are added to the server block of the Nginx configuration. server blocks (similar to the virtual hosts in Apache) are used to encapsulate configuration details and host more than one domain off of a single server.

Example of a server block in nginx.conf

/etc/nginx/nginx.conf
server {
    . . .
    server_name example.com www.example.com;
    . . .
}

Permanently Redirect file (301 Redirect)

In this scenario, we want to permanently redirect page1.html to page2.html and /folder1 to /folder2. This is a 301 redirect and is the best way to ensure that users and search engines are directed to the correct page.

Open the Nginx configuration file. The location of the config file will vary depending on your setup.

sudo nano /etc/nginx/nginx.conf

nginx.conf may also call some other config files, so also check:

sudo nano /etc/nginx/sites-enabled/default

If you followed a previous guide setting up multiple domains in Nginx, your config may be located in somewhere like:

sudo nano /etc/nginx/sites-enabled/example.com

Can’t find the config file?

In the Nginx config file, look for the server block and paste in your required redirect (without the . . . dots!).

/etc/nginx/nginx.conf
server {
    . . .

    # Custom Redirects
    rewrite ^/page1.html$ /page2.html permanent;
    rewrite ^/folder1$ /folder2 permanent;

    . . .
}

Save file and exit. (Press CTRL + X, press Y and then press ENTER)

Check that the Nginx config file is valid.

sudo nginx -t

If valid, reload Nginx config.

sudo service nginx reload

Let me know in the comments if this helped. Follow me @DevAnswers or read more.

1 Star2 Stars3 Stars4 Stars5 Stars 5.00 (1 votes)

Feedback

Your email address will not be published. Required fields are marked *

We use Markdown to style comments, like on Github and Reddit.
To do a line break, type two spaces after the sentence.
You can add inline code by wrapping it in backticks: `code here`

    To do an entire block of code  
    type four spaces before the line
    and it will appear in a block like this.
    <-- four empty spaces