subdomain to folder in nginx

How To Redirect Subdomain To Folder in NGINX

When you move a subdomain to a subfolder on your website, you need to redirect the subdomain to subdirectory to avoid broken links and maintain SEO. Here’s how to redirect subdomain to folder in NGINX. You can use it to redirect subdomain to subfolder in Ubuntu/Debian/CentOS/Redhat/Fedora and other Linux systems.

 

How To Redirect Subdomain To Folder in NGINX

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

 

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 Block IP Address in NGINX

 

2. Redirect Subdomain to Folder in NGINX

Just add the following server block in your server configuration, inside http block.

server {
    server_name blog.example.com;
    return 301 http://www.example.com/blog$request_uri;
}

In the above code replace blog.example.com with your subdomain, and /blog with your subdirectory. The above server block will listen to all requests sent to blog.example.com, due to the server_name directive. It redirects all those requests to /blog subdirectory of your website. $request_uri is the URL stub after subdomain name, in requested URL. We return 301 code to cause a permanent redirect.

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

Bonus Read : Top 10 SSL Certificate Providers for Website

 

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! Now NGINX will redirect subdomain to subfolder for your website.

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