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

.htaccess RewriteRule规则失效求助:带后缀URL无法匹配

解决.htaccess中带-second-version的RewriteRule失效问题

Got it, let's break down why your updated RewriteRule isn't working and fix it step by step.

问题根源

The main issue here is rule order and greedy regex matching. Your original rule (^new-jersey/(.*)) uses the greedy (.*) wildcard, which captures everything after /new-jersey/—including the -second-version suffix. Since Apache processes RewriteRules top to bottom, if your original rule comes before the new one, it will match requests like /new-jersey/city_example-second-version first, and the [L] flag tells Apache to stop processing further rules. That means your new rule never gets a chance to run.

解决方案

Here are two straightforward fixes, depending on your preference:

1. 调整规则顺序(推荐)

Move the -second-version rule above your original rule. This way, Apache will check for the suffix first, and only fall back to the original rule if the suffix isn't present. Also, add a $ at the end of each regex to ensure we match the full URL path (prevents partial matches that could cause unexpected behavior):

# Handle requests with the -second-version suffix first
RewriteRule "^new-jersey/(.*)-second-version$" "location.php?c=$1" [NC,L]

# Handle standard requests without the suffix
RewriteRule "^new-jersey/(.*)$" "location.php?c=$1" [NC,L]

2. 修改原规则排除后缀(可选)

If you don't want to reorder rules, you can update the original rule to explicitly exclude requests ending with -second-version using a negative lookahead. This ensures the original rule only matches paths that don't have your suffix:

# Match only requests that DON'T end with -second-version
RewriteRule "^new-jersey/(.*)(?!-second-version)$" "location.php?c=$1" [NC,L]

# Handle the suffix-specific requests
RewriteRule "^new-jersey/(.*)-second-version$" "location.php?c=$1" [NC,L]

额外调试技巧

  • If you need to support URLs with an optional trailing slash (like /new-jersey/city_example-second-version/), adjust the regex to include /? before the $:
    RewriteRule "^new-jersey/(.*)-second-version/?$" "location.php?c=$1" [NC,L]
    
  • To verify which rule is being matched, you can enable Apache's RewriteLog (temporarily, for debugging) to see the rule matching process in detail.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:37:03