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

寻求.htaccess正则表达式:拦截异常索引URL的重定向规则

解决.htaccess中特定URL的重定向与访问控制问题

Hey there, let's sort out this .htaccess rule issue you're working on. Your goal is clear: let users access http://example.com/index.php or any path like http://example.com/anything-else, but redirect (or block) URLs that append extra content to index.php—like http://example.com/index.php/anything-else. Let's fix your current approach.

The problem with your existing rule

Your current rule checks the QUERY_STRING for index.php/, but that's not the right place to look. In URLs like http://example.com/index.php/anything-else, the /anything-else part is part of the path info, not the query string (the query string is the stuff after ?). So your condition won't actually catch those unwanted URLs.

The corrected .htaccess configuration

Here's the adjusted setup that will do exactly what you need:

RewriteEngine On

# Redirect URLs where index.php has additional path appended (e.g., index.php/anything-else)
RewriteRule ^index\.php/.+$ /send-them-to-404/? [L,R=301]

# Optional: If you want to return a 404 error directly instead of redirecting, use this line instead
# RewriteRule ^index\.php/.+$ - [L,R=404]

Breakdown of the rules

Let's walk through what each part does:

  • RewriteEngine On: Turns on Apache's rewrite module—this is mandatory for any rewrite rules to work.
  • ^index\.php/.+$: This regex targets any URL path that starts with index.php/ followed by one or more characters. The ^ anchors to the start of the path, \. escapes the dot (since dots are special in regex), and .+ matches any sequence of characters after the slash.
  • /send-them-to-404/?: This is the URL you want to redirect users to. The trailing /? ensures any existing query string from the original URL gets stripped.
  • [L,R=301]: The L flag tells Apache this is the last rule to process if it matches. The R=301 sets a permanent redirect (use R=302 if you need a temporary redirect instead).
  • The optional rule skips the redirect and directly returns a 404 error—use this if you prefer to block those URLs outright rather than sending users to a separate 404 page.

What this achieves

With these rules in place:

  • http://example.com/index.php remains accessible (it doesn't match the rewrite rule)
  • http://example.com/anything-else is fully allowed (the path doesn't start with index.php/)
  • Any URL like http://example.com/index.php/foo, http://example.com/index.php/bar/baz, etc., gets redirected to your 404 page (or returns a 404 error directly, if you use the optional rule).

内容的提问来源于stack exchange,提问作者shellshock

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:13:27