Signup/Sign In
PUBLISHED ON: FEBRUARY 27, 2023

How to redirect subdomain to a sub folder/directory using Nginx?

In this tutorial, we will explain how to use nginx to redirect a subdomain to a subdirectory. This practice can be helpful to prevent broken links and maintain SEO, you must redirect a subdomain to a subdirectory when moving it to a subfolder on your website.

How to redirect a domain to a subdirectory in nginx server?

For demonstration we are going to redirect app.domain.com to /app sub-directory.

Create the configuration file for the domain in sites-available (or sites-enabled) sub-directory of nginx configuration directory i.e. /etc/nginx/sites-available/app.domain.com.conf.

$ sudo vim /etc/nginx/sites-available/app.domain.com.conf

Two different methods to send a user to different domain:

URL string and subdomain will be permanently redirected to the subdirectory. Use one of these methods and put these lines in the configuration file.

Method 1: Using rewrite.

server {
  listen 80;
  server_name app.domain.com www.app.domain.com;
  rewrite ^ http://domain.com/app/$request_uri? permanent;
}

Method 2(recommended): for nginx version 0.9.1 or higher. Using return with status code 301(Moved permanently) or 302 (found).

server {
  listen 80;
  server_name app.domain.com www.app.domain.com;
  return 301 http://www.domain.com/app/$request_uri;
}

Replace app.domain.com and domain.com/app/ with your subdomain and subdirectory in the code above. All of the queries made to your website's app.domain.com will be redirected to domain.com/app/. After the subdomain name in the requested URL $request_uri(URL stub after subdomain name). We issue a 301 redirection code in our response.

Finally, You can save and exit the file.

Verify our configuration, then launch Nginx.

It is a recommended practice to test new configurations before loading them to the production server because a single syntax mistake will prevent the Nginx service from running, which will prevent users from accessing your website. You can use the following command to do so.

$ sudo nginx -t -c /etc/nginx/sites-available/app.domain.com.conf

Enable the site if no issues were discovered. In order to accomplish this, we must build a symbolic link between the site configuration file and the sites-enabled directory using the following command:

$ sudo ln -s /etc/nginx/sites-available/app.domain.com.conf /etc/nginx/sites-enabled/app.domain.com.conf

Finally, Start/Restart/Reload the server to load the changes:

$ sudo systemctl restart nginx

or

$ sudo service nginx restart


About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.