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

求可覆盖多变体URL的Apache Rewrite正则表达式

Apache Rewrite Rule to Keep Only the Final Path Segment

Got it, let's solve this problem. You need an Apache Rewrite rule that strips off everything starting from /index.php/module/action/param1/ all the way up to the second-to-last path segment, leaving only the final piece of the URL.

The Rewrite Rule

Here's the rule that will handle all your examples and random variants:

RewriteEngine On
RewriteRule ^index.php/module/action/param1/.*/([^/]+)$ /$1 [L,R=301]

Breakdown of How It Works

Let's break down each part so you understand what's happening:

  • ^index.php/module/action/param1/: This anchors the match to the exact prefix you specified—we only target URLs that start with this string.
  • .*: This matches any characters (all the intermediate path segments) that come after the initial prefix.
  • /([^/]+)$: This captures the final path segment. [^/]+ grabs all characters that aren't a slash (so it stops at the end of the last segment), and $ ensures we're at the very end of the URL.
  • /$1: This is the target URL—we replace the entire matched string with just the captured final segment, rooted at your domain.
  • [L,R=301]: L tells Apache this is the last rule to apply for this request. R=301 sends a permanent redirect, which is good for SEO (search engines will update their indexes to the new URL). If you just want a temporary redirect for testing, swap it to R=302.

Testing Against Your Examples

Let's verify with a couple of your test cases:

  • Input: /index.php/module/action/param1/static/PFBC/js/jquery/help/faq
    Output: /faq
  • Input: /index.php/module/action/param1/legal/asset/css/asset/signup/user/rss/legal/legal/profile/rss/blog/main/rss/rss/b/rss/rss/rss/rss/rss/rss/rss/comment-blog
    Output: /comment-blog
  • Input: https://example.com/index.php/module/action/param1/static/PFBC/js/jquery/rss/static/css/js/jquery/smoothness/templates/themes/datelove/img/icon/xml/sitemap/user/help/rss/legal/rss/comment-picture
    Output: https://example.com/comment-picture

Important Notes

  • Make sure the mod_rewrite module is enabled in your Apache server configuration.
  • If you're using this in a .htaccess file, ensure your server's AllowOverride directive is set to All or FileInfo to permit Rewrite rules.
  • Permanent redirects (301) are cached by browsers, so test with 302 first to make sure everything works as expected before switching to 301.

内容的提问来源于stack exchange,提问作者Undefined-Variables

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:27:28