How to Redirect based on URL in Apache


redirect based on url in apache

RWhen you move your website or certain web pages on it, you need to redirect website visitors based on URL in Apache. This will tell both search engines as well as website visitors that your website has moved. Apache allows you to accomplish this with the help of mod_rewrite module. Let us take a look at how to redirect based on URL in Apache.

 

How to Redirect based on URL in Apache

Here are the steps to redirect based on 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 .htacces file

Open your .htaccess file in a text editor.


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

 

2. Redirect based on URL

Let’s say you want to redirect a single URL /foo to another url /bar in the same server but you don’t want to change the address in browser, then add the following lines to your .htaccess file


RewriteEngine on
RewriteRule "^/foo\.html$" "/bar.html" [PT]

 

If you want to change the address in browser,


RewriteEngine on
RewriteRule "^/foo\.html$" "/bar.html" [R]

 

You can also use the Redirect directive


RewriteEngine on
Redirect "^/foo\.html$" "/bar.html"

 

If you want to redirect a specific URL to a different server/domain, then add the following lines to your .htaccess file


#With mod_rewrite
RewriteEngine on
RewriteRule "^/foo\.html$" "http://new.example.com/bar.html$" [R,L]

 

If you want to redirect all URLs in a folder /docs/ to same folder in a different server


#With mod_rewrite
RewriteEngine on
RewriteRule "^/docs/(.+)" "http://new.example.com/docs/$1" [R,L]

 

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]

 

That’s it! Now Apache will automatically redirect website visitors as well as search engine bots based on URL

 

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!