301 Redirect for All Subdirectories

I am changing domain names for a WordPress site and want to set up a structure like so:

If a user accesses olddomain.com/page, he will be re-directed to newdomain.com/page, etc. In other words, only the pre-slash part of the domain would change. I want to do this for all pages under the old domain.

Read More

So far, I have only been able to get olddomain.com to re-direct to newdomain.com, but not any of the sub-directories (for example, olddomain.com/page does not re-direct to newdomain.com/page). Here is my .htaccess file:

# BEGIN GD-SSL
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_USER_AGENT} ^(.+)$
RewriteCond %{SERVER_NAME} ^newdomain.com$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Header add Strict-Transport-Security "max-age=300"
</IfModule>
# END GD-SSL


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

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

Does anyone know what I did wrong?

Related posts

2 comments

  1. You must put all of the redirect rules before your routing rules. The wordpress rules route everything to index.php, including anything you intend to redirect. So the redirects must happen before any sort of internal routing happens.

    Simply put your redirect rule before the wordpress rules:

    # BEGIN GD-SSL
    <IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_USER_AGENT} ^(.+)$
    RewriteCond %{SERVER_NAME} ^newdomain.com$
    RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
    Header add Strict-Transport-Security "max-age=300"
    </IfModule>
    # END GD-SSL
    
    RewriteEngine On
    RewriteCond %{HTTP_HOST} olddomain.com$ [NC]
    RewriteRule ^(.*)$ https://newdomain.com/$1 [L,R=301]    
    
    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    
    # END WordPress
    
  2. Change your .htaccess to the below code on the old domain:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www.olddomain.com$ [NC] 
    RewriteRule ^(.*)$ http://newdomain.com/$1 [R=301,L]
    </IfModule>
    

    This will redirect the entire website on a page by page basis.

Comments are closed.