.htaccess路径深度缩减优化:能否将3条规则合并为1条?
Great question! You absolutely can merge those three rules into one concise, efficient rule—no need for multiple lines to handle this URL path shortening. Let’s walk through how to do it.
The Core Goal
You want to strip out the /products/i/ segment from URLs like:
https://example.com/en/products/i/dance-show-blabla/STUYXhzEYT
And map them to:
https://example.com/en/dance-show-blabla/STUYXhzEYT
The Combined Rule
Here’s the single rule that achieves this. Choose the version that fits your needs:
Option 1: Internal Rewrite (Server-Side Only)
Use this if you want the server to serve the content at the shortened path without changing the URL in the user’s browser:
RewriteEngine On RewriteRule ^([a-z]{2})/products/i/([^/]+)/([^/]+)/?$ /$1/$2/$3 [L]
Option 2: External 301 Redirect (SEO-Friendly)
Use this if you want to update the URL in the browser (critical for preserving SEO value and avoiding duplicate content):
RewriteEngine On RewriteRule ^([a-z]{2})/products/i/([^/]+)/([^/]+)/?$ /$1/$2/$3 [L,R=301]
Breaking Down the Regex
Let’s explain each part so you understand how it works:
^([a-z]{2}): Captures the two-letter language code (e.g.,en) into the first backreference$1. If your language codes can be longer (likeen-US), adjust this to^([a-z-]+)instead./products/i/: Matches the exact segment we want to remove from the URL path.([^/]+): Captures the slug (e.g.,dance-show-blabla) into$2—this matches any character except a forward slash.([^/]+): Captures the unique ID (e.g.,STUYXhzEYT) into$3./?$: Allows an optional trailing slash at the end of the URL, making the rule flexible for both/pathand/path/.
Why This Works Better
This single rule replaces multiple rules by capturing all necessary segments in one regex pattern. It’s more maintainable, easier to read, and avoids potential conflicts that can come with multiple overlapping rules.
Notes
- Ensure
mod_rewriteis enabled on your Apache server. - Place this rule in your root
.htaccessfile (the same directory where theenfolder resides). - If you’re using the 301 redirect, test with
R=302first to avoid caching issues, then switch toR=301once you confirm it works.
内容的提问来源于stack exchange,提问作者gyurielf

