redirect subfolder to subdomain in nginx

How to Redirect Subfolder to Subdomain in NGINX

Sometimes you may need to redirect subdirectory to subdomain or redirect folder to subdomain during website migration, for SEO purposes and to avoid broken links. Here’s how to redirect subfolder to subdomain in NGINX. You can use it to redirect folder to subdomain in Ubuntu/Debian/CentOS/Redhat/Fedora and other Linux systems.

 

How to Redirect Subfolder to Subdomain in NGINX

Here are the steps to redirect subfolder to subdomain in NGINX. Let’s say you want to redirect subfolder example.com/blog to subdomain blog.example.com

 

1. Open NGINX configuration file

If you are using NGINX’s main configuration file nginx.conf, without virtual hosts, then open terminal and run the following command

$ sudo vi /etc/nginx/nginx.conf

If you have configured separate virtual hosts for your website (e.g www.website.com), such as /etc/nginx/sites-enabled/website.conf then open its configuration with the following command

$ sudo vi /etc/nginx/sites-enabled/website.conf

Bonus Read : How to Redirect Subdomain to Folder in NGINX

 

2. Redirect Subdomain to Folder in NGINX

Just add the following location block in your server configuration, inside server block, above “location / ” block.

location ^~ /blog {
    rewrite ^/blog/?(.*)$ https://blog.example.com/$1 permanent;
}

In the above code replace blog.example.com with your subdomain, and /blog with your subdirectory. The above location block will listen to all requests sent to example.com/block. It redirects all those requests to blog.example.com subdomain of your website. $1 is the URL stub after subfolder in requested URL. We add permanent keyword at the end of rewrite directive to cause a permanent redirect.

So it will permanently redirect subfolder to subdomain along with URL string.

Bonus Read : How to Block IP Address in NGINX

 

3. Restart NGINX

Finally, run the following command to check syntax of your updated config file.

$ sudo nginx -t

 

Bonus Read : How to Redirect Location to Another Domain in NGINX

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

 

That’s it! Hopefully the above tutorial will help you redirect subfolder to subdomain in NGINX for your website.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform for small & medium businesses. Build dashboards, charts & reports for your business in minutes. Get insights from data quickly. Try it for free today!