寻求.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 withindex.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]: TheLflag tells Apache this is the last rule to process if it matches. TheR=301sets a permanent redirect (useR=302if 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.phpremains accessible (it doesn't match the rewrite rule)http://example.com/anything-elseis fully allowed (the path doesn't start withindex.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

