You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用.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:

  1. When someone visits examplesite.com/platform/sign-in.php, your Redirect 301 tells the browser to jump to /platform/login/.
  2. Your RewriteRule then internally maps /platform/login/ back to platform/sign-in.php.
  3. Apache detects this internal mapping and triggers the Redirect again, 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 RewriteCond regex: 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=301 sends a permanent SEO-friendly redirect, and L tells Apache to stop processing further rules after this one.
  • The internal rewrite rule: Remains mostly the same—[NC] ignores case sensitivity, and L stops 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.so loaded, and your site's directory has AllowOverride All set (so .htaccess rules 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:44:06