Sometimes you may need to redirect one URL to another URL in Apache server. You can easily do this using mod_rewrite (.htaccess). In this article, we will look at how to rewrite URL to another URL in Apache.
How to Rewrite URL to Another URL in Apache
Here are the steps to rewrite URL to another URL in Apache.
1. Enable mod_rewrite
If you have already enabled mod_rewrite on your Apache server, you can skip this step. Otherwise, run the following commands as per your Linux distribution.
$ sudo a2enmod rewrite
Open Apache configuration file in a text editor.
$ sudo vi /etc/apache2/httpd.conf OR $ sudo vi /etc/httpd/httpd.conf
Look for the following line.
#LoadModule rewrite_module modules/mod_rewrite.so
Uncomment it by removing # at its beginning. If you don’t find this line, add it afresh.
Also look for the following Directory tag and change AllowOverride from None to All.
. . .
. . .
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
. . .
. . .
2. Redirect URL to another URL
Create/Open .htaccess file at your website’s root folder.
$ sudo vi /var/www/html/.htaccess
Add any of the following lines to it depending on your requirement.
Let us say you want to redirect URL /project.html to /product/project.html then add the following Redirect command
Redirect /project.html /product/project.html
The first argument above is the old URL and second argument is the new URL. If you want to redirect old URL to another domain then mention the full URL along with new domain as second argument above.
Redirect /project.html https://newdomain.com/product/project.html
You may also use RewriteRule to accomplish above redirection
RewriteRule ^project.html$ /product/project.html$1 [R=301,NC,L]
In the above rule, we use ^ & $ in first argument to specify URLs beginning & ending with /project.html. We also use $1 in second argument to include any query string parameters from old URL. R=301 indicates permanent redirection.
If you want to redirect directory /product to /data you can do so using Redirect statement.
Redirect /project/ /data/
If you want to redirect folder from domain to another, mention the full URL of new folder location, along with new domain name.
Redirect /project/ https://example.com/data/
3. Restart Apache Server
Restart Apache server to apply changes.
$ sudo service apache2 restart
In this article, we have looked at different ways to redirect one URL to another in Apache server. You can modify them as per your requirement. Using Redirect directive is the easiest and simplest way to rewrite/redirect URL in Apache server. If you don’t have access to .htaccess file, you can also add these Redirect statements as-is in your server’s virtual host file, within <VirtualHost> tag. However, RewritreRule works only within .htaccess file.