How to Redirect a Web Page with Apache
The most common way of redirecting a web page is through adding specific rules to a `.htaccess` on an Apache webserver.
Apache (Apache HTTP Server) can redirect using different tools. The simplest way is to use tools from mod_alias extension.
Use Redirect Directive
The redirect directive lets you execute simple and one-page redirects with Apache. This directive is a part of “mod_alias” module and requires at the minimum two arguments: the old URL and the new URL.
To accomplish a simple redirect in your server configuration uses the following code:
<VirtualHost *:80> ServerName www.domain1.com Redirect / http://www.domain2.com </VirtualHost> <VirtualHost *:80> ServerName www.domain2.com . . . . . . </VirtualHost>
This redirect instructs the browser to direct all requests for "www.domain1.com" to "www.domain2.com". It's only for a single page, not for the entire website.
Note, that the redirect directive leads to a 302 or a temporary redirect. In the case you want to have a permanent redirect, use 301 redirect or Redirect permanent. (Learn more about HTTP Status Codes).
Redirect 301 /oldlocation http://www.domain2.com/newlocation
Redirect permanent /oldlocation http://www.domain2.com/newlocation
Use the Redirectmatch Directive
If you want to redirect more than one page, use the redirectMatch directive. It allows you to identify directory matching patterns using constant expressions.
The redirectMatch directive matches patterns in parentheses and sets the matched text in the redirect using “$1” where 1 is the first group of text. Subsequent groups are given numbers sequentially.
If you want to match each request for something within the "/blog" directory to a subdomain named "blog.new-website.com", you can use the following example:
RedirectMatch 301 /blog(.*) http://www.blog.new-website.com$1
This command will redirect the Blog of the old website to the Blog of a new one.
Use mod_rewrite URLs
For more complicated tasks such as manipulating the query string, use mod_rewrite. It doesn't redirect but rewrites URLs. The main difference between rewriting and redirecting is that rewriting a URL involves the server returning a different request than the one provided by the client.
If you want to hide URLs with sensitive or endangered data, rewriting can be useful for you.
To rewrite the old URL to the new one follow this rule.