.htaccess 🚂 Redirecting a domain to another one

Share on twitter
Share on linkedin
Share on facebook
Share on whatsapp
Share on email
Share on twitter
Share on linkedin
Share on facebook
Share on whatsapp
Share on email

You own several domain names for the same site? Here is a simple method to redirect all your secondary domain names to a main domain name using the .htaccess file.

The codes present in this article are to be placed in the file named .htaccess at the root of all the secondary sites which must carry out the redirection. Remember to adapt this code with your information: protocol (http or https) and domain name.

.htaccess : Redirection of a whole domain to another one

This first code redirects all URLs to our main domain, here https://newdomain.com keeping the path, but not the subdomain. That is, URLs with a subdomain such as www.olddomaine.com/chemin and those without sub-domains such as olddomain.com/path will be redirected to https://newdomaine.com/chemin. If you don't want to keep the path in the destination URL, just delete $1.


   # Redirect all URL to https://newdomaine.com/$1
   RewriteEngine On
   RewriteRule (.*)$ https://newdomain.com/$1 [R=301,L]

.htaccess : Domain redirection with sub-domain management

If we want a more precise redirection of the subdomains, we will have to use the following code. Here, all URLs with the subdomain1 subdomain (of the form subdomain1.olddomain.com/path) will be redirected to subdomain1.newdomain.com/pathand for the subdomain subdomain2. All other forms of URLs will be redirected to https://newdomain.com/ (which will redirect URLs of the form olddomain.com/path and www.olddomaine.com/chemin to https://newdomaine.com/chemin).


    RewriteEngine On

    # Redirect subdomaine1.olddomain.com/* to https://subdomaine1.newdomaine.com/$1
    RewriteCond %{HTTP_HOST} ^subdomaine1.olddomain.com$
    RewriteRule (.*)$ http://subdomaine1.newdomain.com/$1 [R=301,L]

    # Redirect subdomaine2.olddomain.com/* to https://subdomaine2.newdomaine.com/$1
    RewriteCond %{HTTP_HOST} ^subdomaine2.olddomain.com$
    RewriteRule (.*)$ http://subdomaine2.newdomain.com/$1 [R=301,L]

    # Redirect all another to https://newdomaine.com/$1
    RewriteRule (.*)$ https://newdomain.com/$1 [R=301,L]

Julien .MA Jacob
Developer WordPress
Julien MA Jacob - Developer WordPress
🧙♂️ Passionate about the web and programming with always lots of projects in mind 👨💻 | About page
  Discussion of the article
Subscribe to our newsletter
Notify of
guest
1 Commentary
most popular
latest oldest
Inline Feedbacks
View all comments
Manual

Hello, Thanks for this tutorial, It's strange because after the modification in htaccess the redirection works only for the domain name. Do you have any idea why? Thanks to you ;)