Redirect OLD URL to NEW URL in Nginx

Are you having website migration or some changes on the website structure categories or slugs? Then you will definitely need to do redirection rules to match with your old urls to new urls.

If you are using a Nginx server and want to redirect your OLD URL to NEW URL, you may use the following rule to add it in the server directive of your domain config block. So, please open the your domain config file under this file path via ssh or ftp etc/nginx/sites-available/example.com

 

OLD URL

http://www.example.com/blog/mynewblogpost.html

NEW URL

http://www.example.com/news/mynewblogpost.html

REDIRECT RULE, please replace your old category "blog" to new category "news"

rewrite ^/news(.*) http://www.example.com/news$1 permanent;

 

Final Nginx server config block will be look like below:

server {
     listen 80;
     #listen 443 ssl;
    
     # Your Domain Name
     server_name example.com www.example.com;

     # Root Directory
     root /var/www/html/www.example.com;
     index index.php index.html index.html;

     # Redirect Rules
     rewrite ^/news(.*) http://www.example.com/news$1 permanent;

}

 

After making necessary changes, please save the config file and please restart Nginx server using the folliwng commands:

# To check server config files

$ sudo nginx -t

# To restart nginx service

$ sudo systemctl restart nginx

 

Then, it's ready to test and you may try to access your OLD URL and it'll be automatically redirected to NEW URL now. Enjoy!

 


Published on: 24/11/2021, 2:03 AM