How to Redirect Only Root Domain via .htaccess While Preserving Subdirectories


2 views

When you need to redirect just the root domain (e.g., example.com/) to another URL while keeping all subdirectories intact (e.g., example.com/admin, example.com/blog), standard redirect methods in .htaccess can accidentally catch these subpaths. Here's how to implement a precise root-only redirect.

The key is to use mod_rewrite with careful pattern matching. We'll use two conditions:

  1. Check the request is exactly the root path
  2. Exclude all requests with paths

Place this in your .htaccess file:


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

The ^/$ pattern matches only the root path. The R=301 makes it a permanent redirect, and L stops further processing.

Be aware these approaches WON'T work properly:

  • Redirect 301 / https://newdomain.com (redirects everything)
  • RewriteRule ^$ https://newdomain.com (less reliable)

If you need to preserve query strings:


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

When implementing domain redirects, developers often need to redirect just the root URL (e.g., example.com/) while maintaining all subdirectories (e.g., example.com/blog, example.com/admin). This requires precise .htaccess configuration to avoid blanket redirects.

Most tutorials suggest these problematic approaches:


# WRONG - Redirects EVERYTHING
Redirect 301 / https://newsite.com

# WRONG - May cause redirect loops
RewriteRule ^$ https://newsite.com [R=301,L]

Here's the exact .htaccess configuration that targets only the root domain:


RewriteEngine On

# Condition: Only match empty path (root)
RewriteCond %{REQUEST_URI} ^/$

# Rule: Redirect root to new domain
RewriteRule ^$ https://newsite.com [R=301,L]

# Preserve all other URLs
RewriteRule ^(.*)$ - [L]

For a site moving from old-example.com to new-example.com:


<IfModule mod_rewrite.c>
    RewriteEngine On
    
    # Root domain redirect
    RewriteCond %{HTTP_HOST} ^old-example\.com$ [NC]
    RewriteCond %{REQUEST_URI} ^/$
    RewriteRule ^$ https://new-example.com [R=301,L]
    
    # All other URLs remain
    RewriteCond %{REQUEST_URI} !^/$
    RewriteRule ^ - [L]
</IfModule>

Verify the redirect works correctly with these curl commands:


# Should redirect
curl -I http://example.com/

# Should NOT redirect
curl -I http://example.com/subpage

For sites using HTTPS or specific server configurations:


# With HTTPS enforcement
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^$ https://new-domain.com [R=301,L]