Domain redirection is a common practice on the internet, allowing visitors to a website to be automatically redirected to another domain. This method is often used for rebranding, merging websites, or for simpler URL memorability. Below, you'll find five specific guides on how to accomplish this process using various scripts and technologies.
1. Redirecting via .htaccess on Apache Server
For web servers running on Apache, you can use the .htaccess
file for redirection. This approach enables quick and efficient redirection without the need to modify the website's code.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain\.com [NC]
RewriteRule ^(.*)$ http://newdomain.com/$1 [L,R=301]
This code activates the mod_rewrite
module, checks if the request pertains to a specific domain (olddomain.com
), and then redirects all requests to newdomain.com
, while preserving the path and query parameters.
2. Redirecting in Nginx
If your website runs on an Nginx server, redirection is configured in the server's configuration file. Below is an example of how to redirect an entire domain:
server {
server_name olddomain.com;
return 301 $scheme://newdomain.com$request_uri;
}
This example defines a server block for olddomain.com
and redirects all requests to newdomain.com
, while retaining the original path and query parameters.
3. Redirecting via JavaScript
For cases where you don't have access to server configuration or prefer client-side redirection, you can use JavaScript:
if (window.location.hostname == "olddomain.com") {
window.location.href = "http://newdomain.com" + window.location.pathname + window.location.search;
}
This script checks the hostname in the URL, and if it matches olddomain.com
, it redirects users to newdomain.com
, preserving the original path and parameters.
4. Redirecting with PHP
If your website is built with PHP, you can perform redirection using the following script placed at the beginning of your index.php
file:
if ($_SERVER['HTTP_HOST'] == 'olddomain.com') {
header('Location: http://newdomain.com'.$_SERVER['REQUEST_URI'], true, 301);
exit;
}
This code checks the HTTP_HOST
and redirects visitors to newdomain.com
, while preserving the path and query parameters.
5. Redirecting via HTML
Though less common, for simple cases, you can use pure HTML with the meta refresh tag in the HTML document's header:
<meta http-equiv="refresh" content="0; url=http://newdomain.com">
This tag immediately redirects users to newdomain.com
. The main disadvantage is that this approach does not send an HTTP status code for redirection, which may have negative implications for SEO.
When choosing a redirection method, it's important to consider the technologies available on your server and whether preserving SEO domain ranking is crucial. Always test redirection in a safe environment before applying it to a production server.