Website Design Principles 2025

Read More

Tidy Tip: Redirects with .htaccess

17th March, 2025

Redirecting URLs with a Similar Structure Using .htaccess.

If you need to move a section of your website to a new domain while maintaining the same URL structure, you can use .htaccess to handle the redirects automatically. This is particularly useful when transitioning content without manually mapping each individual URL.

The Problem

Imagine you have a website, example.com, and you want to move a specific section such as /old-section/ to newsite.com, keeping the same structure.

For example:

Instead of manually redirecting each page, we can use .htaccess to automate this process.

The Solution

The following .htaccess rule will redirect all URLs under /old-section/ to newsite.com/new-section/ while keeping everything after /old-section/ unchanged.

RewriteEngine On

# Redirect any URL under /old-section/ to the new domain while maintaining structure
RewriteCond %{REQUEST_URI} ^/old-section(/.*)?$
RewriteRule ^ https://newsite.com/new-section%1 [R=301,L]

# Handle the exact `/old-section/` case to ensure a clean redirect
RewriteRule ^old-section/$ https://newsite.com/new-section/ [R=301,L]

Handling Deeper URL Structures

If the new site requires a deeper folder structure (e.g., moving /old-section/ to /new-subsection/new-section/), we can modify the rule to account for the additional path.

For example:

Updated .htaccess rule:

RewriteEngine On

# Redirect with deeper structure
RewriteCond %{REQUEST_URI} ^/old-section/([^/]+)(/.*)?$
RewriteRule ^ https://newsite.com/new-subsection/new-%1/new-section%2 [R=301,L]

# Handle exact `/old-section/` case
RewriteRule ^old-section/$ https://newsite.com/new-subsection/new-section/ [R=301,L]

How It Works

1. Enable RewriteEngine: Ensures URL rewriting is active.
2. RewriteCond %{REQUEST_URI} ^/old-section/([^/]+)(/.*)?$:
– Captures the first directory under /old-section/ as %1.
– Captures everything after it as %2.
3. RewriteRule ^ https://newsite.com/new-subsection/new-%1/new-section%2 [R=301,L]:
%1 replaces the first directory after /old-section/.
%2 maintains any remaining URL structure.
R=301 sets a permanent redirect.
L ensures no further rules are applied once this matches.
4. Explicit rule for /old-section/: Ensures a clean redirect if the URL is exactly /old-section/.

Testing and Best Practices

By implementing this .htaccess rule, you can seamlessly transition a section of your site to a new domain while maintaining consistency and avoiding manual effort.

Luke

Web Design Posts

11th February, 2025

SSL Certificates

30th August, 2024

A Subtle Redesign

Recent Posts

8th February, 2025

Marketing Costs 2025

11th January, 2025

18+ Years in Business