Search code examples
apache.htaccesshttp-redirectmod-rewrite

Trying to redirect pages from old domain to new domain through .htaccess


I'm trying to do a redirect using .htaccess and am running into a problem I can't identify.

What I want to do: Redirect all pages from my old domain to my new domain. For example: https://www.olddomain.com/fun-blog-post/ would forward to https://www.newdomain.com/blog/fun-blog-post/

My code:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com/$1 [OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com/$1
RewriteRule (.*)$ https://www.newdomain.com/blog/$1 [L,R=301]

Unexpected Behavior: When I type in olddomain.com, it takes me directly to newdomain.com. However, if I type in olddomain.com/new-blog-post, it doesn't redirect at all. It pulls up a 404 error and just displays olddomain.com/new-blog-post.

I've checked the following two threads already.

.htaccess redirect all pages to new domain

Redirect from old domain to new domain not work

However, I cannot figure this one out. I've tried a few different tweaks, most of which I don't remember, but this seems to be the best solution I can come up with. Can someone please help me see what I am doing wrong?


Solution

  • RewriteCond %{HTTP_HOST} ^olddomain.com/$1 [OR]
    RewriteCond %{HTTP_HOST} ^www.olddomain.com/$1
    RewriteRule (.*)$ https://www.newdomain.com/blog/$1 [L,R=301]
    

    As written, this wouldn't redirect anything because of the erroneous /$1 at the end of the CondPattern on the RewriteCond directives.

    It should be written like this (the two RewriteCond directives can be combined into one):

    RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com [NC]
    RewriteRule (.*) https://www.newdomain.com/blog/$1 [R=301,L]
    

    This needs to go near the top of the .htaccess file, before any existing directives.

    NB: Test first with a 302 (temporary) redirect to avoid potential caching issues.

    You will need to clear your browser cache before testing.

    When I type in olddomain.com, it takes me directly to newdomain.com

    This may be due to a cached redirect, or "something else". The rule you posted would not even trigger this redirect.