求可覆盖多变体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]:Ltells Apache this is the last rule to apply for this request.R=301sends 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 toR=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_rewritemodule is enabled in your Apache server configuration. - If you're using this in a
.htaccessfile, ensure your server'sAllowOverridedirective is set toAllorFileInfoto 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
相关产品推荐
相关产品推荐

