How to Redirect Subdirectory to Root in NGINX

When you move your website from a subfolder to the root location of your domain, you need to redirect all its pages and subdirectories to their new location. In this article, we will look how to redirect to subdirectory to root in NGINX.

How to Redirect Subdirectory to Root in NGINX

Here are the steps to redirect subdirectory to root in NGINX.

1. Open NGINX configuration file

The NGINX configuration file is located at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf depending on your installation. Open terminal and run the following command to open NGINX configuration file.

$ sudo vi /etc/nginx/nginx.conf

Also read : How to Redirect 403 to 404 in Apache

2. Redirect subdirectory to root

Let us say you want to redirect /blog subdirectory to the root location of your domain. Add the following location block in your NGINX configuration file. Modify /blog with your subfolder name.

location ^~ /blog {
      rewrite ^/blog(.*)$ $1 last; 

The above location block will match all URLs starting with /blog and redirect them to the root location, while preserving its URL stub. $1 above ensures that URL part is retained during redirection. For example, will be redirected to

Also read : How to Install pip in Ubuntu

3. Restart NGINX Server

Restart NGINX server to apply changes.

$ sudo nginx -t 
$ sudo systemctl restart nginx

Also read : How to Enable Gzip in NGINX

Now NGINX will automatically redirect all URLs starting with /blog to the root location.

Leave a Reply

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