When you move many web pages and directories, you need to add redirects from their old URL to their new ones to let search engines and website visitors know that your content has moved. Many times, these new URLs can be obtained by replacing underscore with hyphen. So you can easily redirect all these pages with a single redirect command instead of adding multiple, separate statements. Let us take a look at how to replace underscore with hyphen in URL in Apache.
How to Replace Underscore with Hyphen in URL in Apache
Here are the steps to replace underscore with 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. Replace underscore with hyphen in URL string
Let’s say you have a folder /articles/ whose URLs have underscore, and you want to replace them with hyphens. So just add the following lines to your .htaccess file
RewriteEngine On RewriteRule ^(/?articles/.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N] RewriteRule ^(/?articles/.*/[^/]*?)_([^/_]*)$ $1-$2 [R=301]
In the above code, you can update the folder name “articles” with other location, if you want. If you want to apply the above rules for all URLs, remove the folder name altogether, like so
RewriteEngine On RewriteRule ^(/.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N] RewriteRule ^(/.*/[^/]*?)_([^/_]*)$ $1-$2 [R=301]
The above code the first rewriterule basically loops through your URL, replacing underscores with hyphens, until there is one or less left. That’s when the second rule kicks in and replaces the underscore with a hyphen, and adds a permanent redirect.
You can also add the above code to your virtual host config file, instead of .htaccess.
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]