从THE_REQUEST提取纯路径至变量的htaccess规则精简需求
Extract Clean Path from THE_REQUEST with .htaccess (Simplified)
Hey argon, nice work getting the multi-line solution working—let’s condense that into a couple of concise, elegant rules that cover every edge case you listed perfectly.
The Simplified Rules
# Extract clean path (strip trailing slashes & query strings) RewriteCond %{THE_REQUEST} \s/+([^\s?]+)(?:/?\?|\s) RewriteRule ^ - [E=TRGT:%1] # Explicitly set empty value for root requests RewriteCond %{THE_REQUEST} \s/(?:\s|\?) RewriteRule ^ - [E=TRGT:]
How It Works
Let’s break down each rule to show it handles all your requirements:
Main Path Extraction Rule
- The regex
\s/+([^\s?]+)(?:/?\?|\s)targets the path segment inTHE_REQUEST:\s/+matches the space before the request path, plus any leading slashes (so it ignores the initial/)([^\s?]+)captures the core path—this matches everything that’s not a space or question mark, so it automatically excludes query strings(?:/?\?|\s)matches either an optional trailing slash followed by a query string, or the closing space of the request line. This ensures trailing slashes are stripped from the captured value.
- This single rule handles paths with extensions, subfolders, trailing slashes, and query strings all in one pass.
- The regex
Root Request Handling
- The regex
\s/(?:\s|\?)matches root-level requests (likeGET / HTTP/1.1orGET /?foo=bar HTTP/1.1). - It explicitly sets the
TRGTenvironment variable to an empty string, which aligns with your requirement of having an empty/undefined value for the root domain.
- The regex
Test Case Verification
All your expected scenarios are covered:
example.com→TRGT=(empty)example.com/→TRGT=(empty)example.com/some-word→TRGT=some-wordexample.com/some-word/→TRGT=some-wordexample.com/some-word/?foo=bar→TRGT=some-wordexample.com/another_word/→TRGT=another_wordexample.com/folder/file.ext→TRGT=folder/file.extexample.com/some/other.dot?bar=foo→TRGT=some/other.dotexample.com/thing.ext/?foo=bar&bar=foo→TRGT=thing.ext
Why This Beats the Multi-Line Approach
- Reduces 4 conditional rules to just 2, eliminating redundant processing
- Uses a single regex capture to handle trailing slashes and query strings simultaneously
- Explicitly addresses root requests without relying on multiple conditional passes, making the logic clearer and more efficient
内容的提问来源于stack exchange,提问作者argon
相关产品推荐
相关产品推荐

