How to Remove Underscore & Hyphen in URL in NGINX


remove underscore & hyphen in url in nginx

When you move many web pages and directories, you need to redirect their old URLs to new ones, so that search engines and website visitors know that content has moved. However, it can be tedious to setup so many different rules if you have many web pages and directories. In most cases, the new URLs can be obtained by simply removing underscore & hyphen from URL. This allows you to redirect all pages with just one rule. Let us look at how to remove underscore & hyphen in URL in NGINX.

 

How to Remove Underscore & Hyphen in URL in NGINX

Here are the steps to remove underscore & 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. Remove Underscore & Hyphen in URL

Let’s say you want to remove underscore & hyphens in all URLs on your website, then add the following rules to your .htaccess file.

rewrite ^(.*)[-_](.*)$ $1$2 permanent;

 

If the above rule doesn’t work for you, try

rewrite ^(/[^/]*)[-_]([^/]*)$ $1$2 permanent;

 

Both rules, capture and remove underscore & hyphens repeatedly until all of them are matched.

Place the above rule above the first location block. If you only want URLs in a location block to be replaced, then place it inside a location block.

 

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 is a really useful trick to redirect multiple URLs located in different directories and folders at one go, without writing multiple, separate rules.

 

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!