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.


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 & redirect 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 >> but does not passed the path, meaning when you hit you still load

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\$ [NC]
  RewriteRule ^{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} ^$ [OR]
  RewriteCond %{HTTP_HOST} ^$ [OR]
  RewriteCond %{HTTP_HOST} ^$
  RewriteRule (.*)$$1 [R=301,L]


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.



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 ^{REQUEST_URI} [R=301,L,NE]

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

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