How to Remove Underscore & Hyphen in URL in Apache

remove underscore & hyphens in url in apache

When you move your web pages and directories, you need to redirect old URLs to new ones. Many times, you can obtain the new URLs by simply removing underscore & hyphen from old ones. This way you can use a single redirect rule to redirect many different pages, instead of using multiple, separate statements. Let us take a look at how to remove underscore & hyphen in URL in Apache.


How to Remove Underscore & Hyphen in URL in Apache

Here are the steps to remove underscore & hyphen in URL in Apache.

Before you proceed, please ensure that you have enabled .htaccess (mod_rewrite) in Apache. If not, then here’s how you can do it:


Place your .htaccess file in the root document folder of your website (/var/www/html).


1. Open .htaccess file

Open .htaccess file in a text editor

$ sudo vim /var/www/html/.htaccess


2. Remove underscore & hyphens in URL

Just add the following lines to remove underscore and hyphens from all your URLs.

RewriteEngine on

#1 Redirect rule to convert _ to -
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.*?)_+[_-]*(.+?)\sHTTP [NC]
RewriteRule ^ /%1-%2 [L,NE,R=302]

#2--Redirect  "/?load=/foo" to "/foo"--#
RewriteCond %{THE_REQUEST} /\?load=/([^\s&]+) [NC]
RewriteRule ^ /%1? [NE,L,R=302]

#3--Rewrite "/foo" to "/?load=/foo--#
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)/?$ /?load=/$1 [L,QSA]


The above code will first replace all underscores with hyphens, and then remove the hyphens to make a permanent redirect.

If the above code doesn’t work for you, you can try the following shorter one.

# Replace all but the last underscore with dashes internally:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^_]*)_([^_]*_.*)$ $1-$2 [N]

# Replace the last underscore and issue a HTTP permanent redirect:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=301]



This is a very useful trick to redirect a number of URLs & directories at one go, without writing multiple, separate statements.


3. Restart Apache web server

Restart Apache web server to apply changes

$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]




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!