
How to Create Temporary and Permanent Redirects with Apache and Nginx
Web redirects are fundamental HTTP mechanisms that tell browsers and search engines when content has moved or when users should be routed to different URLs. Whether you’re restructuring your site, handling legacy URLs, or implementing complex routing logic, properly configuring redirects on Apache and Nginx servers is crucial for maintaining SEO rankings, user experience, and preventing broken links. In this guide, we’ll explore how to implement both temporary (302) and permanent (301) redirects on both web servers, covering configuration syntax, real-world scenarios, troubleshooting common issues, and performance considerations.
Understanding HTTP Redirect Types
Before diving into server configurations, it’s essential to understand the difference between redirect types and their implications:
Redirect Type | HTTP Status Code | Browser Behavior | Search Engine Impact | Use Case |
---|---|---|---|---|
Permanent Redirect | 301 | Caches redirect permanently | Transfers SEO juice to new URL | Site restructuring, domain changes |
Temporary Redirect | 302 | Does not cache redirect | Keeps SEO juice on original URL | Maintenance pages, A/B testing |
The choice between 301 and 302 significantly impacts both user experience and SEO. Search engines like Google treat 301 redirects as permanent moves, transferring link equity and rankings to the target URL. Meanwhile, 302 redirects signal temporary moves, keeping the original URL in search results.
Apache Redirect Configuration
Apache offers multiple methods to implement redirects, with the most common approaches using mod_rewrite and the Redirect directive. Here’s how to configure both types:
Using the Redirect Directive
The simplest method for basic redirects uses Apache’s built-in Redirect directive:
# Permanent redirect (301)
Redirect permanent /old-page.html http://example.com/new-page.html
Redirect 301 /old-directory/ http://example.com/new-directory/
# Temporary redirect (302)
Redirect temp /maintenance.html http://example.com/under-construction.html
Redirect 302 /temp-page.html http://example.com/temporary-location.html
Using mod_rewrite for Advanced Redirects
For more complex redirect logic, mod_rewrite provides greater flexibility:
# Enable mod_rewrite
RewriteEngine On
# Permanent redirects (301)
RewriteRule ^old-page\.html$ /new-page.html [R=301,L]
RewriteRule ^blog/(.*)$ /articles/$1 [R=301,L]
# Temporary redirects (302)
RewriteRule ^temp-redirect\.html$ /temporary-page.html [R=302,L]
RewriteRule ^maintenance$ /under-construction.html [R=302,L]
# Redirect entire domain
RewriteCond %{HTTP_HOST} ^olddomain\.com [NC]
RewriteRule ^(.*)$ http://newdomain.com/$1 [R=301,L]
Apache Virtual Host Configuration
For domain-wide redirects, configure them within virtual host blocks:
<VirtualHost *:80>
ServerName oldsite.com
ServerAlias www.oldsite.com
# Redirect all traffic to new domain
Redirect 301 / https://newsite.com/
</VirtualHost>
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
# Specific page redirects
Redirect 301 /old-product.html /products/new-product.html
Redirect 302 /sale /products/temporary-sale.html
</VirtualHost>
Nginx Redirect Configuration
Nginx handles redirects through the return directive and rewrite module, offering clean syntax and excellent performance:
Using the Return Directive
The return directive is the preferred method for simple redirects in Nginx:
# Permanent redirects (301)
location /old-page.html {
return 301 /new-page.html;
}
location /old-directory/ {
return 301 /new-directory/;
}
# Temporary redirects (302)
location /maintenance.html {
return 302 /under-construction.html;
}
location /temp-page {
return 302 /temporary-location.html;
}
Using Rewrite Rules
For pattern matching and complex redirects, use rewrite rules:
# Permanent redirects with pattern matching
rewrite ^/blog/(.*)$ /articles/$1 permanent;
rewrite ^/products/old-category/(.*)$ /products/new-category/$1 permanent;
# Temporary redirects
rewrite ^/temp-redirect(.*)$ /temporary-page$1 redirect;
# Conditional redirects
if ($host = 'oldsite.com') {
rewrite ^/(.*)$ http://newsite.com/$1 permanent;
}
Complete Nginx Server Block Example
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
# Permanent redirects
location /old-section/ {
return 301 /new-section/;
}
# Temporary redirect for maintenance
location /admin/ {
return 302 /maintenance.html;
}
# Pattern-based redirects
location ~* ^/blog/(\d+)/(.*)$ {
return 301 /articles/$1/$2;
}
# Catch-all for remaining requests
location / {
try_files $uri $uri/ =404;
}
}
# Redirect entire domain
server {
listen 80;
server_name oldsite.com www.oldsite.com;
return 301 http://newsite.com$request_uri;
}
Real-World Use Cases and Examples
Here are practical scenarios where redirects solve common web development challenges:
E-commerce Site Restructuring
When reorganizing product categories:
# Apache
RewriteRule ^products/electronics/(.*)$ /tech/$1 [R=301,L]
RewriteRule ^products/clothing/(.*)$ /fashion/$1 [R=301,L]
# Nginx
rewrite ^/products/electronics/(.*)$ /tech/$1 permanent;
rewrite ^/products/clothing/(.*)$ /fashion/$1 permanent;
HTTP to HTTPS Migration
Forcing SSL connections:
# Apache
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Nginx
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
Seasonal Campaign Management
Temporary redirects for marketing campaigns:
# Apache - Temporary holiday promotion
RewriteRule ^sale$ /holiday-promotion.html [R=302,L]
# Nginx - Black Friday redirect
location /sale {
return 302 /black-friday-deals;
}
Performance Comparison and Benchmarks
Different redirect methods have varying performance implications:
Server | Method | Performance Impact | Memory Usage | Best For |
---|---|---|---|---|
Apache | Redirect directive | Low | Minimal | Simple static redirects |
Apache | mod_rewrite | Medium | Moderate | Complex pattern matching |
Nginx | return directive | Very Low | Minimal | All simple redirects |
Nginx | rewrite rules | Low | Low | Pattern-based redirects |
Nginx generally outperforms Apache in redirect handling due to its event-driven architecture. In benchmark tests, Nginx can handle approximately 2-3x more redirect requests per second compared to Apache under similar conditions.
Common Issues and Troubleshooting
Here are frequent problems and their solutions:
Redirect Loops
Infinite redirect loops occur when redirects point back to themselves:
# Problem: This creates a loop
RewriteRule ^(.*)$ /$1 [R=301,L]
# Solution: Add proper conditions
RewriteCond %{REQUEST_URI} !^/new-location/
RewriteRule ^old-location/(.*)$ /new-location/$1 [R=301,L]
Case Sensitivity Issues
URLs are case-sensitive by default:
# Apache - Case insensitive matching
RewriteRule ^old-page\.html$ /new-page.html [R=301,L,NC]
# Nginx - Case insensitive location
location ~* ^/old-page\.html$ {
return 301 /new-page.html;
}
Query String Preservation
Maintaining URL parameters during redirects:
# Apache - Preserve query strings
RewriteRule ^old-search$ /new-search.php? [R=301,L,QSA]
# Nginx - Query strings are preserved automatically
location /old-search {
return 301 /new-search.php;
}
Best Practices and Security Considerations
Follow these guidelines for robust redirect implementations:
- Use 301 for permanent changes: When content permanently moves, always use 301 redirects to preserve SEO value
- Avoid redirect chains: Multiple consecutive redirects slow down page loading and can confuse search engines
- Validate redirect targets: Ensure destination URLs exist and are accessible to prevent broken user experiences
- Monitor redirect performance: Use tools like Google Search Console to identify redirect issues
- Consider mobile implications: Test redirects on mobile devices, as they may behave differently
Security Considerations
Prevent open redirect vulnerabilities by validating destination URLs:
# Apache - Restrict redirect destinations
RewriteCond %{QUERY_STRING} ^url=([^&]+)
RewriteCond %1 ^https?://example\.com/
RewriteRule ^redirect$ %1? [R=302,L]
# Nginx - Validate redirect targets
map $arg_url $redirect_url {
~^https?://example\.com/(?<path>.*)$ $path;
}
location /redirect {
if ($redirect_url) {
return 302 /$redirect_url;
}
return 400;
}
Testing and Validation
Always test redirects thoroughly before deploying to production:
# Test redirects with curl
curl -I http://example.com/old-page.html
# Should return: HTTP/1.1 301 Moved Permanently
# Check redirect chains
curl -L -I http://example.com/old-page.html
# Test with specific user agents
curl -H "User-Agent: Mozilla/5.0" -I http://example.com/old-page.html
Use online tools like HTTP Status Checker or browser developer tools to verify redirect behavior. For production environments, consider using monitoring tools to track redirect performance and identify issues before they impact users.
For hosting solutions that provide optimized Apache and Nginx configurations, consider managed VPS services or dedicated servers that offer pre-configured environments for web applications.
Remember that proper redirect implementation is crucial for maintaining search engine rankings and providing seamless user experiences. Take time to plan your redirect strategy, test thoroughly, and monitor performance after deployment to ensure optimal results.

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.