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

server {
    . . .
    . . .

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/

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!).

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 if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

Leave a reply

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