15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
30.10.2024

Redirect via .htaccess: The Complete Guide to Managing Redirects on Apache Servers

Redirects are among the most critical tools in a web administrator's arsenal. Whether you're restructuring your site's URLs, migrating to a new domain, or enforcing HTTPS, setting up redirects correctly can mean the difference between retaining your search engine rankings and losing them entirely. On Apache-based servers, the .htaccess file is the go-to solution for implementing powerful, flexible redirects without touching global server configuration.

In this comprehensive guide, we'll cover everything you need to know about .htaccess redirects — from the fundamentals to advanced configurations — so you can manage your website traffic with confidence.

Table of Contents

  1. What Is .htaccess?
  2. Why Use Redirects?
  3. Types of Redirects Explained
  4. How to Set Up Redirects via .htaccess
  5. Advanced Redirect Scenarios
  6. Best Practices for .htaccess Redirects
  7. Troubleshooting Common Redirect Issues
  8. Conclusion

1. What Is .htaccess? {#what-is-htaccess}

The .htaccess file — short for hypertext access — is a directory-level configuration file used by Apache web servers. Unlike global server configuration files (such as httpd.conf), which require root-level access and a server restart to apply changes, .htaccess operates at the directory level and takes effect immediately upon saving.

Key characteristics of .htaccess:

  • Scope: Settings apply to the directory where the file is placed and all of its subdirectories.
  • No restart required: Changes take effect instantly without restarting the Apache server.
  • Versatility: Beyond redirects, .htaccess can handle URL rewriting, access control, custom error pages, MIME type configuration, caching rules, and more.
  • Placement: Typically placed in the root directory (public_html or www) of your website.

> Important: For .htaccess to function, the Apache server must have AllowOverride set to All in the server configuration. If you're on a managed hosting environment, this is usually enabled by default.

If you're running your own server, whether on a VPS Hosting plan or a Dedicated Server, you'll have full control over Apache's configuration and can enable AllowOverride as needed.

2. Why Use Redirects? {#why-use-redirects}

Redirects serve multiple critical purposes in website management. Here's a breakdown of the most common use cases:

URL Structure Changes

When you restructure your website — for example, migrating from /old-page.html to /new-page.html — users with bookmarks or links pointing to the old URL will encounter a 404 Not Found error. A redirect automatically forwards them to the correct destination.

Domain Migration

Moving your website to a new domain? Without proper redirects, all traffic to your old domain will simply disappear. Domain-level redirects ensure that every visitor and every search engine crawler is forwarded seamlessly to the new domain.

SEO Value Preservation

Search engines assign authority and ranking signals to specific URLs. When content moves without a proper redirect, those signals are lost. A correctly implemented 301 redirect passes the majority of link equity (often referred to as "PageRank") from the old URL to the new one, protecting your organic search rankings.

Enforcing Canonical URLs

Duplicate content is a common SEO problem. For example, http://yoursite.com, https://yoursite.com, http://www.yoursite.com, and https://www.yoursite.com can all serve the same content, confusing search engines. Redirects enforce a single canonical version of your URL.

Enforcing HTTPS

If you've installed an SSL Certificate on your domain, you'll want to ensure all visitors are automatically served the secure HTTPS version of your site. An .htaccess redirect handles this automatically.

Improved User Experience

Users who click outdated links or type old URLs should never hit a dead end. Redirects ensure they always land on the right page, reducing bounce rates and improving overall satisfaction.

3. Types of Redirects Explained {#types-of-redirects}

HTTP redirects are defined by status codes. Understanding which code to use in which situation is fundamental to implementing redirects correctly.

Status CodeNameUse Case
301Permanent RedirectContent has permanently moved to a new URL
302Temporary Redirect (Found)Content has temporarily moved
303See OtherResponse to a POST request; redirect to a GET resource
307Temporary RedirectTemporary move; method preserved
308Permanent RedirectPermanent move; method preserved

301 Redirect — Permanent Redirect

The 301 redirect is the most commonly used redirect in SEO and website management. It signals to browsers and search engines that the content at the original URL has permanently moved to a new location. Search engines will update their indexes to reflect the new URL and transfer the majority of the original page's ranking authority.

Use a 301 when:

  • You've permanently moved a page or restructured your URLs
  • You're migrating to a new domain
  • You're consolidating duplicate content
  • You're enforcing www vs. non-www or HTTP vs. HTTPS

302 Redirect — Temporary Redirect

The 302 redirect tells browsers and search engines that the move is temporary and that the original URL will eventually be restored. Search engines generally do not transfer link equity for 302 redirects and will continue to index the original URL.

Use a 302 when:

  • You're running a temporary promotion or A/B test
  • You're performing maintenance and temporarily redirecting users
  • The original URL will return to active use in the near future

> Common mistake: Many developers use 302 redirects when they actually intend a permanent redirect. Always use 301 for permanent moves to avoid SEO penalties and confusing search engine crawlers.

4. How to Set Up Redirects via .htaccess {#how-to-set-up-redirects}

Before making any changes, always create a backup of your existing .htaccess file. A single syntax error can cause a 500 Internal Server Error and take your site offline.

Accessing Your .htaccess File

You can access your .htaccess file via:

  • FTP/SFTP client (e.g., FileZilla) — navigate to your root directory
  • File Manager in your hosting control panel (cPanel, DirectAdmin, etc.)
  • SSH terminalnano /var/www/html/.htaccess

> Note: .htaccess is a hidden file. Make sure your FTP client or file manager is configured to show hidden files (files beginning with a dot).

Redirect a Single Page

The simplest redirect use case is forwarding one specific URL to another. Use the Redirect directive:

Redirect 301 /old-page.html https://www.yoursite.com/new-page.html

Breakdown:

    Redirect — the Apache directive for simple redirects
    301 — the HTTP status code (permanent redirect)
    /old-page.html — the old URL path (relative to the document root)
    https://www.yoursite.com/new-page.html — the full destination URL
    
    For a temporary redirect, simply replace 301 with 302:
    Redirect 302 /promo-page.html https://www.yoursite.com/sale.html
    —
    Redirect Multiple Specific Pages
    If you need to redirect several individual pages, list each redirect on a separate line:
    Redirect 301 /old-page-1.html https://www.yoursite.com/new-page-1.html
    Redirect 301 /old-page-2.html https://www.yoursite.com/new-page-2.html
    Redirect 301 /old-page-3.html https://www.yoursite.com/new-page-3.html
    —
    Redirect an Entire Domain
    When migrating your entire website to a new domain, use mod_rewrite to redirect all traffic while preserving URL paths:
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^olddomain.com$ [NC,OR]
    RewriteCond %{HTTP_HOST} ^www.olddomain.com$ [NC]
    RewriteRule ^(.*)$ https://www.newdomain.com/$1 [L,R=301]
    Breakdown:
    
    RewriteEngine On — activates the mod_rewrite Apache module
    RewriteCond %{HTTP_HOST} ^olddomain.com$ — matches requests to olddomain.com
    [NC] — case-insensitive matching
    [OR] — logical OR between conditions (matches either www or non-www)
    RewriteRule ^(.*)$ https://www.newdomain.com/$1 — redirects all traffic, preserving the URL path ($1 captures everything after the domain)
    [L,R=301] — L means this is the last rule to process; R=301 specifies a permanent redirect
    
    —
    Redirect www to Non-www
    Choosing between www and non-www as your canonical domain is an important SEO decision. Once chosen, redirect all traffic to the preferred version.
    Redirect www → non-www:
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www.yoursite.com$ [NC]
    RewriteRule ^(.*)$ https://yoursite.com/$1 [L,R=301]
    Redirect non-www → www:
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^yoursite.com$ [NC]
    RewriteRule ^(.*)$ https://www.yoursite.com/$1 [L,R=301]
    > Tip: Be consistent. Pick one canonical version and stick with it. Inconsistency between www and non-www creates duplicate content issues and dilutes your SEO signals.
    —
    Redirect HTTP to HTTPS
    Once you've installed an SSL certificate, you should force all traffic to use the secure HTTPS protocol. This is one of the most important redirects for both security and SEO, as Google uses HTTPS as a ranking signal.
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    Breakdown:
    
    RewriteCond %{HTTPS} off — checks whether the current request is NOT using HTTPS
    %{HTTP_HOST} — dynamically inserts the hostname (works for any domain)
    %{REQUEST_URI} — preserves the full URL path and query string
    
    Combined HTTP to HTTPS + non-www to www redirect:
    RewriteEngine On
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ^www. [NC]
    RewriteRule ^ https://yoursite.com%{REQUEST_URI} [L,R=301]
    —
    Redirect a Directory
    To redirect an entire directory to a new location:
    RedirectMatch 301 ^/old-directory/(.*)$ https://www.yoursite.com/new-directory/$1
    This uses RedirectMatch, which supports regular expressions, allowing you to match and redirect all URLs within a specific directory while preserving the file path.
    —
    Redirect Based on Query String
    Sometimes you need to redirect URLs that contain specific query parameters:
    RewriteEngine On
    RewriteCond %{QUERY_STRING} ^id=123$
    RewriteRule ^page.php$ https://www.yoursite.com/new-page/? [L,R=301]
    The trailing ? in the destination URL strips the original query string from the redirected URL.
    —
    5. Advanced Redirect Scenarios {#advanced-redirect-scenarios}
    Redirect to a Maintenance Page
    During scheduled maintenance, redirect all visitors to a temporary maintenance page while allowing your own IP address through:
    RewriteEngine On
    RewriteCond %{REMOTE_ADDR} !^123.456.789.000$
    RewriteCond %{REQUEST_URI} !/maintenance.html$
    RewriteRule ^(.*)$ /maintenance.html [L,R=302]
    Replace 123.456.789.000 with your actual IP address.
    Force Trailing Slash on Directories
    Inconsistent trailing slashes can create duplicate content. Force a trailing slash on directory URLs:
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !/$
    RewriteRule ^(.*)$ /$1/ [L,R=301]
    Custom 404 Error Page with Redirect
    While not a traditional redirect, configuring a custom 404 page improves user experience when broken links are encountered:
    ErrorDocument 404 /404.html
    —
    6. Best Practices for .htaccess Redirects {#best-practices}
    Following these best practices will help you avoid common pitfalls and ensure your redirects perform optimally.
    ✅ Always Use 301 for Permanent Changes
    Use a 301 redirect whenever content has permanently moved. This ensures search engines transfer ranking authority to the new URL and update their indexes accordingly.
    ✅ Back Up Before Editing
    Before making any changes to your .htaccess file, download a copy to your local machine. A syntax error can cause a 500 Internal Server Error, taking your site offline instantly.
    ✅ Test All Redirects After Implementation
    Use tools like:
    
    Redirect Checker (redirect-checker.org)
    Screaming Frog SEO Spider — crawls your site and identifies redirect chains
    Google Search Console — monitors how Google processes your redirects
    curl command in terminal: curl -I https://yoursite.com/old-page.html

    ✅ Avoid Redirect Chains

    A redirect chain occurs when URL A redirects to URL B, which redirects to URL C. Each hop adds latency and dilutes the SEO value passed through the chain. Always redirect directly to the final destination.

    Bad:

    /page-a → /page-b → /page-c

    Good:

    /page-a → /page-c
    /page-b → /page-c

    ✅ Avoid Redirect Loops

    A redirect loop occurs when URL A redirects to URL B, which redirects back to URL A. This causes a browser error and makes the page inaccessible. Always verify your redirect logic before deploying.

    ✅ Keep .htaccess Lean

    Every request to your server causes Apache to read the .htaccess file. A bloated file with dozens of unnecessary rules can slow down your server. Keep only the rules you actively need.

    ✅ Use HTTPS Everywhere

    If you haven't already, install an SSL certificate and redirect all HTTP traffic to HTTPS. This is a baseline security requirement and a confirmed Google ranking factor. AlexHost offers SSL Certificates that can be deployed quickly across your domains.

    ✅ Monitor Redirects in Google Search Console

    After implementing redirects — especially after a domain migration — monitor Google Search Console's Coverage and URL Inspection reports to ensure Google is correctly indexing your new URLs.

    7. Troubleshooting Common Redirect Issues {#troubleshooting}

    500 Internal Server Error

    Cause: Syntax error in .htaccess

    Fix: Carefully review your .htaccess syntax. Even a missing space or bracket can cause this error. Restore your backup and re-apply changes one rule at a time.

    Redirect Not Working

    Cause: mod_rewrite may not be enabled, or AllowOverride is not set to All

    Fix: Ensure mod_rewrite is enabled (a2enmod rewrite on Ubuntu/Debian) and that AllowOverride All is set in your Apache virtual host configuration.

    Redirect Loop (ERR_TOO_MANY_REDIRECTS)

    Cause: Two or more redirect rules are pointing at each other

    Fix: Review your rules carefully. For HTTPS redirects, ensure your RewriteCond correctly checks %{HTTPS} status. Some server environments (e.g., behind a load balancer) require checking %{HTTP:X-Forwarded-Proto} instead.

    Redirect Passes Query Strings Incorrectly

    Cause: Query strings are not being handled as expected

    Fix: Use %{QUERY_STRING} in your RewriteCond and append ? to the destination URL to strip or preserve query strings as needed.

    .htaccess File Not Being Read

    Cause: The file may be named incorrectly or placed in the wrong directory

    Fix: Ensure the file is named exactly .htaccess (with the leading dot and no file extension) and is placed in the correct directory.

    8. Conclusion {#conclusion}

    Mastering .htaccess redirects is an essential skill for any web developer, SEO professional, or systems administrator working with Apache-based hosting environments. Whether you're redirecting a single page, migrating an entire domain, enforcing HTTPS, or consolidating your canonical URLs, the .htaccess file provides a powerful and flexible mechanism to handle it all — without requiring access to global server configuration files.

    The key takeaways:

    • Use 301 redirects for permanent moves to preserve SEO value
    • Use 302 redirects only for genuinely temporary situations
    • Always back up your .htaccess file before editing
    • Avoid redirect chains and loops to maintain performance and SEO integrity
    • Test every redirect after implementation using reliable tools

    The quality of your hosting environment also plays a significant role in how effectively redirects perform. A fast, well-configured server ensures that redirect processing adds minimal latency to your users' experience. Whether you need a flexible VPS Hosting environment with full Apache control, a powerful Dedicated Server for high-traffic websites, or an easy-to-manage Shared Web Hosting plan with .htaccess support built in, AlexHost has the infrastructure to support your needs.

    If you're managing multiple websites or domains, consider pairing your hosting with Domain Registration through AlexHost to streamline your entire web infrastructure under one reliable platform.

    By implementing the techniques covered in this guide, you'll ensure that your visitors always land on the right page, your search engine rankings remain protected through every site change, and your server runs efficiently without unnecessary redirect overhead.

    15%

    Save 15% on All Hosting Services

    Test your skills and get Discount on any hosting plan

    Use code:

    Skills
    Get Started