How to Replace Underscore With Hyphen in URL in NGINX


replace underscore with hyphen in url in nginx

Sometimes, you may move multiple web pages and directories on a website, and change their URLs to have hyphens instead of underscores. In fact, this is a common practice when moving bulk number of pages to new location. In such cases, it can be really tedious to write separate rewrite rules for so many URLs and directories. It might be better to simply replace underscores in the old URLs with hyphens to obtain their new URLs. Let us take a look at how to replace underscore with hyphen in URL in NGINX.

 

How to Replace Underscore With Hyphen in URL in NGINX

Here are the steps to replace underscore with hyphen 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 Underscore in URL string

Let’s say you have moved your entire website, or just a number of directories and pages, and your their new URLs can be obtained by simply substituting underscore with hyphens. Add the following lines to your location block

location ~ _ {
    rewrite "^([^_]*)_([^_]*)_([^_]*)_(.*)$" $1-$2-$3-$4 last;
    rewrite "^([^_]*)_(.+)$" $1-$2 last;
    return 301 $uri;
}

The above code will replace 1-3 underscores every internal redirect. It also supports up to 30 underscores in direct http request.

 

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 character 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!