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

Member

by lia , in category: General Help , a year ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by brock , a year 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.

Member

by enrico , 8 months ago

@lia 

Additionally, you can also use a 301 permanent redirect or a 302 temporary redirect in the rewrite rule, depending on your specific use case.


Here is an updated example using a 301 permanent redirect:

1
2
3
location /dir1 {
  rewrite ^/dir1/(.*)$ /dir2/$1 permanent;
}


And here is an example using a 302 temporary redirect:

1
2
3
location /dir1 {
  rewrite ^/dir1/(.*)$ /dir2/$1 redirect;
}


By specifying 'permanent' or 'redirect' in the rewrite directive, you can control whether the redirect is a permanent or temporary one. Remember to test the configuration and reload Nginx after making any changes.