How to Replace Characters in URL in NGINX


replace characters in url in nginx

Sometimes when you move a number of web pages to a different folder or directory, you may need to redirect many old URLs to new URLs each of which can be obtained by simply substituting a substring in the old URLs. In such cases, you can replace characters in URL and redirect to the result. Let us take a look at how to replace characters in URL in NGINX.

 

How to Replace Characters in URL in NGINX

Here are the steps to replace characters in URL in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Replace Characters in URL string

Let’s say you have moved a number of directories and pages from URLs which contained the string “product” to new locations which contain the string “items” in them. Add the following lines to your location block


location / {
rewrite ^(.*)product(.*)$ $1items$2;
...
}

 

The first regular expression will match all URLs that contain the string “product” and replace the string with “items”.

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

This trick is very useful if you have many web pages and directories that have been moved to a new location which can be obtained by simply substituting a string in their old URLs. You don’t have to write multiple separate rewrite statements.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!