When you move many web pages and directories to new location, you need to rewrite multiple, separate rewrite rules to redirect old URLs to new ones. However, if the new URLs are very similar to the old ones, then you might want to redirect pages by substituting some characters in URLs. This way you don’t have to write many rewrite rules and can do everything at one go. Let us take a look at how to replace characters in URL string in Apache.
How to Replace Characters in URL String in Apache
Here are the steps to replace characters in URL string 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. Add trailing slash
Let’s say you have a number of URLs and directories, all of which contain the string “old-version”, that have moved to new locations, all of which contain the string “new-version”
In that case, add the following lines to your .htaccess file
RewriteEngine On RewriteRule ^(.*)old-version(.*)$ $1new-version$2 [R=301,L,NC]
In the above rewrite rule, the first regular expression will match all URLs that contain the string “old-version” and replace them with the new string “new-version”.
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]
This trick is really helpful if you have too many URLs and directories that need to be redirected, and want to avoid writing too many rewrite rules for your web server.