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


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


by brock , 3 months ago


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 (, 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 to, you would use the following location block:
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:
sudo nginx -t

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

sudo systemctl reload nginx

Now, when users visit, they will be automatically redirected to