How to redirect users from one dir to another in nginx?

Member

by lia , in category: General Help , 3 months ago

How to redirect users from one dir to another in nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brock , 3 months ago

@lia 

To redirect users from one directory to another in Nginx, you can use the rewrite directive in the server block configuration. Here's an example:

  1. Open the Nginx configuration file for your website. In most cases, it is located in the /etc/nginx/sites-available/ directory and named after your domain (example.com, for instance).
  2. Locate the server block that corresponds to the website or domain where you want to apply the redirect.
  3. Inside the server block, add a new location block to specify the directory or URL path that you want to redirect from. For example, if you want to redirect requests from example.com/dir1 to example.com/dir2, you would use the following location block:
1
2
3
location /dir1 {
  rewrite ^/dir1/(.*)$ /dir2/$1 permanent;
}


  1. Save the configuration file and exit your text editor.
  2. Test the Nginx configuration file for syntax errors:
1
sudo nginx -t


If there are no errors, proceed to reload Nginx for the changes to take effect:

1
sudo systemctl reload nginx


Now, when users visit example.com/dir1, they will be automatically redirected to example.com/dir2.