如何用.htaccess配置RewriteRule与301重定向解决URL重定向循环
Fixing the 301 Redirect Loop for SEO-Friendly URLs
Ah, that classic redirect loop issue—let me break down why this is happening and how to fix it cleanly.
Why the Loop Happens
Your current setup creates an infinite cycle:
- When someone visits
examplesite.com/platform/sign-in.php, yourRedirect 301tells the browser to jump to/platform/login/. - Your
RewriteRulethen internally maps/platform/login/back toplatform/sign-in.php. - Apache detects this internal mapping and triggers the
Redirectagain, repeating the cycle until the browser gives up.
The core problem is that Redirect (a mod_alias directive) doesn't distinguish between direct user requests and internal rewrites. We need a way to only redirect when a user directly accesses the old .php URL, not when Apache is internally handling the new URL.
The Solution: Use mod_rewrite with a Condition
Replace your existing rules with this unified mod_rewrite setup (order matters—put the redirect first):
# 301 Redirect direct requests for sign-in.php to login/ RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /platform/sign-in\.php\ HTTP/ RewriteRule ^platform/sign-in\.php$ /platform/login/ [R=301,L] # Internally map login/ to sign-in.php (no visible change to users) RewriteRule ^platform/login/?$ platform/sign-in.php [NC,L]
What Each Part Does
%{THE_REQUEST}: This variable captures the original request line sent by the browser (e.g.,GET /platform/sign-in.php HTTP/1.1). Unlike other variables, it doesn't get modified by internal rewrites—so we can use it to check if the user directly requested the old URL.- The
RewriteCondregex: It matches only when the browser sends a direct request for/platform/sign-in.php, ignoring internal mappings from the new URL. [R=301,L]:R=301sends a permanent SEO-friendly redirect, andLtells Apache to stop processing further rules after this one.- The internal rewrite rule: Remains mostly the same—
[NC]ignores case sensitivity, andLstops processing after mapping the new URL to the PHP file.
Key Notes to Avoid Issues
- Clear browser cache first: 301 redirects are cached aggressively by browsers. Use incognito mode or clear your cache before testing to avoid old cached redirects interfering.
- Ensure mod_rewrite is enabled: Make sure your Apache server has
mod_rewrite.soloaded, and your site's directory hasAllowOverride Allset (so.htaccessrules are applied). - Stick to mod_rewrite: Mixing mod_alias (like
Redirect) and mod_rewrite rules can cause unexpected behavior since they process requests in different orders.
内容的提问来源于stack exchange,提问作者Riffaz Starr
相关产品推荐
相关产品推荐

