Ad

How To Redirect Domains On A Wordpress Site, Including Path?

- 1 answer

I there.

I got a website with 2 different domains pointing to itself.

  1. Domain.com
  2. Domain.com.br

The site loaded both domains and created duplicated content, which have created a giant problem for SEO (both domains loaded the exact same content.

I wish to resolve this problem by redirecting one domain to the other, using [301] redirection.

I want to keep Domain.com.br & redirect Domain.com. Is it possible to do that on the same server?

Till now, I have I came across 2 snippets of codes.

  • First one gives me an internal server error (500).
  • Second one redirected the top level domain (.com >> .com.br) but does not passed the path, meaning when you hit domain.com/path you still load domain.com/path

What do you guys think? How can I resolve that?

<IfModule mod_rewrite.c>

  // This have given me an internal server error 500
  
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC, OR]
  RewriteCond %{HTTP_HOST} ^(www)?domain\.com.br$ [NC]
  RewriteRule ^ https://%1domain.com.br%{REQUEST_URI} [R=301,L,NE]


  // This one also isn't working. Only top domain is redirecting. 
  // Request URL does not pass.
  
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^domain.com$ [OR]
  RewriteCond %{HTTP_HOST} ^www.domain.com$ [OR]
  RewriteCond %{HTTP_HOST} ^www.domain.com.br$
  RewriteRule (.*)$ https://domain.com.br/$1 [R=301,L]

</IfModule>

The following example, will redirect localhost >> localhost/test, but will not redirect localhost/xyz >> localhost/xyz/test

  RewriteCond %{HTTPS} !on [OR]
  RewriteCond %{HTTP_HOST} ^(www\.)?localhost$ [NC]
  RewriteRule ^ http://localhost:8888/test/%{REQUEST_URI} [R=301,L,NE]

Any help would be super helpful. Thank you 🙏

Problem solved

As @anubhava mentioned, codes needs to be topmpost - first ones on the htaccess file.

All the codes I always received worked. Problem was that I placed the rewriting rules after wordpress rules. This prevented my rules to get written, cause the permalinks got written before.

Ad

Answer

Assuming both domains are pointing to same DocumentRoot, you can use this rule in your site root .htaccess:

RewriteEngine On

RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule ^ https://domain.com.br%{REQUEST_URI} [R=301,L,NE]

This rule will redirect to .br domain if HTTPS is not on OR host name in request is domain.com with optional www. before.

Make sure this is your topmost rule and you completely clear browser cache before testing.

Ad
source: stackoverflow.com
Ad