
How to Create Temporary and Permanent Redirects with Apache
Apache redirects are fundamental tools for managing web traffic flow, whether you’re restructuring URLs, migrating domains, or implementing SEO strategies. Understanding the difference between temporary (302) and permanent (301) redirects can make or break your site’s search rankings and user experience. In this guide, we’ll walk through the technical implementation of both redirect types using Apache’s mod_rewrite and Redirect directives, explore real-world scenarios, and cover the gotchas that can trip up even experienced developers.
Understanding Apache Redirect Mechanisms
Apache offers several ways to handle redirects, each with distinct advantages. The two primary methods are the Redirect
directive and mod_rewrite
rules. The Redirect directive is straightforward and efficient for simple redirects, while mod_rewrite provides powerful pattern matching and conditional logic capabilities.
Here’s how they work under the hood: when Apache receives a request, it processes directives in a specific order. Redirect directives are processed during the URL translation phase, while RewriteRules execute during the rewrite phase. This ordering matters when you have complex configurations with multiple redirect types.
Method | Performance | Flexibility | Learning Curve | Best For |
---|---|---|---|---|
Redirect Directive | High | Low | Easy | Simple URL redirects |
mod_rewrite | Medium | Very High | Steep | Complex patterns, conditional redirects |
RedirectMatch | High | Medium | Medium | Regex-based simple redirects |
Implementing Permanent Redirects (301)
Permanent redirects tell search engines and browsers that a resource has moved permanently to a new location. This is crucial for maintaining SEO juice when restructuring sites or changing domains.
Using the Redirect Directive
The simplest approach for permanent redirects uses Apache’s built-in Redirect directive:
# Single page redirect
Redirect 301 /old-page.html http://example.com/new-page.html
# Entire directory redirect
Redirect 301 /old-directory/ http://example.com/new-directory/
# Domain change redirect
Redirect 301 / http://newdomain.com/
Advanced Permanent Redirects with mod_rewrite
For more complex scenarios, mod_rewrite offers powerful pattern matching:
# Enable rewrite engine
RewriteEngine On
# Redirect old blog structure to new format
RewriteRule ^blog/([0-9]{4})/([0-9]{2})/(.+)$ /articles/$1/$2/$3 [R=301,L]
# Force HTTPS redirect
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Remove www prefix permanently
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
# Redirect based on user agent (mobile users)
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|mobile" [NC]
RewriteRule ^(.*)$ http://m.example.com/$1 [R=301,L]
Implementing Temporary Redirects (302)
Temporary redirects indicate that a resource is temporarily located elsewhere but may return to its original location. Search engines typically don’t transfer ranking signals with 302 redirects, making them ideal for maintenance pages or A/B testing scenarios.
# Simple temporary redirect
Redirect 302 /maintenance.html http://example.com/under-construction.html
# Temporary redirect using mod_rewrite
RewriteEngine On
# Redirect during maintenance window
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^192\.168\.1\.100$
RewriteRule ^(.*)$ /maintenance.html [R=302,L]
# Time-based temporary redirect
RewriteCond %{TIME_HOUR} ^(02|03|04)$
RewriteRule ^(.*)$ http://example.com/scheduled-maintenance.html [R=302,L]
# Redirect based on server load (requires mod_evasive or similar)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{LA-U:SERVER_LOAD} >10
RewriteRule ^(.*)$ http://backup.example.com/$1 [R=302,L]
Real-World Use Cases and Examples
E-commerce Product Migration
When restructuring an e-commerce site’s URL structure, maintaining SEO rankings is critical:
# Old structure: /products/category/product-id
# New structure: /shop/category/product-name
RewriteEngine On
# Map old product IDs to new URLs using RewriteMap
RewriteMap productmap txt:/etc/apache2/product-mapping.txt
RewriteRule ^products/([^/]+)/([0-9]+)$ /shop/$1/${productmap:$2} [R=301,L]
The mapping file (/etc/apache2/product-mapping.txt
) would contain:
12345 gaming-laptop-xyz
12346 wireless-mouse-pro
12347 mechanical-keyboard-rgb
Development and Staging Environment Redirects
Managing redirects across different environments requires careful configuration:
# Environment-specific redirects
RewriteEngine On
# Redirect staging URLs to production for crawlers
RewriteCond %{HTTP_HOST} ^staging\.example\.com$ [NC]
RewriteCond %{HTTP_USER_AGENT} (googlebot|bingbot|slurp) [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
# Development environment catch-all
RewriteCond %{HTTP_HOST} ^dev\.example\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/dev-assets/
RewriteRule ^(.*)$ http://www.example.com/$1 [R=302,L]
Configuration Best Practices
Proper redirect implementation requires attention to several critical factors that can impact performance and functionality:
- Always use the [L] flag in RewriteRules to prevent further rule processing after a match
- Order matters – place more specific rules before general ones
- Test with curl to verify response codes:
curl -I http://example.com/old-page
- Use absolute URLs in redirects to avoid confusion and potential redirect loops
- Monitor redirect chains – avoid multiple redirects that slow down page loads
- Enable query string appending with [QSA] flag when needed
Performance Optimization
Redirect performance can significantly impact user experience. Here are some optimization strategies:
# Use RewriteMap for large-scale redirects instead of multiple RewriteRules
RewriteMap redirects txt:/etc/apache2/redirects.txt
RewriteCond ${redirects:%{REQUEST_URI}} ^(.+)$
RewriteRule ^(.*)$ %1 [R=301,L]
# Cache redirect rules in memory for better performance
RewriteMap redirects "txt:/etc/apache2/redirects.txt"
Common Pitfalls and Troubleshooting
Redirect Loops
Redirect loops are among the most frustrating issues developers encounter. They typically occur when redirect rules create circular references:
# WRONG - Creates infinite loop
RewriteRule ^old/(.*)$ /new/$1 [R=301,L]
RewriteRule ^new/(.*)$ /old/$1 [R=301,L]
# CORRECT - Use conditions to prevent loops
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule ^old/(.*)$ /new/$1 [R=301,L]
Debug Configuration Issues
Enable rewrite logging for troubleshooting complex redirect issues:
# In httpd.conf or virtual host
LogLevel alert rewrite:trace6
ErrorLog /var/log/apache2/rewrite.log
Testing Redirect Configurations
Before deploying redirect rules to production, thoroughly test them:
# Test redirect response codes
curl -I -L http://example.com/old-page
# Test with different user agents
curl -I -H "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)" http://example.com/
# Validate redirect chains
curl -I -L -w "%{num_redirects} redirects\n" http://example.com/old-page
Security Considerations and Edge Cases
Redirects can introduce security vulnerabilities if not properly configured. Open redirect vulnerabilities occur when user input influences redirect destinations:
# Vulnerable to open redirects
RewriteCond %{QUERY_STRING} url=(.*)
RewriteRule ^redirect$ %1? [R=302,L]
# Secure alternative - validate destination
RewriteCond %{QUERY_STRING} url=([^&]+)
RewriteCond %1 ^https?://example\.com/.*$ [NC]
RewriteRule ^redirect$ %1? [R=302,L]
Handling Special Characters and Encoding
URLs with special characters require careful handling to prevent breaking redirects:
# Handle URLs with spaces and special characters
RewriteRule ^old%20page\.html$ /new-page.html [R=301,L]
# Use B flag for proper URL encoding
RewriteRule ^old/(.*)$ /new/$1 [R=301,L,B]
When implementing redirects on high-traffic sites, consider using a VPS or dedicated server to ensure optimal performance and reliability. Proper server resources become crucial when handling thousands of redirects with complex pattern matching.
For comprehensive Apache configuration guidance, consult the official Apache mod_rewrite documentation and the Redirect directive reference. These resources provide detailed explanations of advanced features and edge cases that can help you build robust redirect configurations for any scenario.

This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.
This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.