How to Redirect and Keep Original URL using htaccess

Sometimes you may need to redirect domain pages without changing URL in Apache web server. Here’s how to redirect and keep original URL using .htaccess. You can use it to redirect domain or page without changing URL.

 

How to Redirect and Keep Original URL using htaccess

Here are the steps to redirect and keep original URL using htaccess. Before proceeding further, make sure you have setup mod_rewrite and mod_proxy in Apache. Here are the steps to

  1. Enable mod_rewrite in Apache
  2. Enable mod_proxy in Apache

 

Let’s say you want to redirect all pages from your old domain www.example.com to new domain www.example2.com without changing URL

Bonus Read : How to Fix 504 Gateway Error in Apache

 

1. Open .htaccess file

Open Apache web server’s .htaccess file in a text editor. You can modify the following file location as per your server configuration.

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

Bonus Read : How to Fix 500 Internal Server Error in Apache

 

2. Redirect Domain without changing URL

Add the following lines in DOCUMENT_ROOT directory

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^ http://www.example1.com%{REQUEST_URI} [L,NE,P]

Let us look at the above lines.

The first line allows you to use Symbolic links, while second line enables mod_rewrite if it is not enabled already.

RewriteBase allows you to define the base URL for rewrites. RewriteCond checks incoming requests’ HTTP_HOST value to match with your old domain www.example.com

RewriteRule redirects those requests to their new domain www.example1.com. However, since we use P flag in RewriteRule, Apache will handle it as a proxy request and not change URL.

 

Bonus Read : How to Install mod_deflate in Ubuntu/CentOS

 

3. Restart Apache Server

Restart Apache web server

$ sudo systemctl restart apache2

 

Now your Apache web server will automatically redirect domain pages without changing URL.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!