问题
I'm performing several regular expressions on a string inside a variable in order to clean it up for further use in the htaccess rules, but it seems rather cumbersome to do such simple thing in several lines:
RewriteCond %{THE_REQUEST} (?<=\s)(.*?)(?=\s)
RewriteRule ^(.*)$ - [E=HREFPATH:%1]
RewriteCond %{ENV:HREFPATH} (^.*)?\?
RewriteRule ^(.*)$ - [E=HREFPATH:%1]
RewriteCond %{ENV:HREFPATH} /(.*)
RewriteRule ^(.*)$ - [E=HREFPATH:%1]
RewriteCond %{ENV:HREFPATH} (.*)/$
RewriteRule ^(.*)$ - [E=HREFPATH:%1]
How can I reduce this to 2 lines?
Basically I'm looking for a way to encapsulate each as aggregation steps (filter) based on the output of the previous expression, but my humble efforts have failed after trying and web-searching for hours.
The code above does what I need it to do, it's just really ugly (not elegant).
In PHP, or basically any decent(ish) language it could be as simple as:
$HREFPATH = trim(explode(explode(" ",$THE_REQUEST)[1],"?")[0],"/");
-but this is NOT a PHP-related question; merely a simple way to explain what I mean, and what I'm trying to achieve.
I know there may be many RegEx patterns that could (theoretically) work here, but it should be compatible with Apache's RegEx engine.
Any input will be rewarded in kind; thanks in advance.
回答1:
What you are doing in multiple rules can be done in a single like this:
RewriteCond %{THE_REQUEST} \s/+([^?]*?)/*[\s?]
RewriteRule ^ - [E=HREFPATH:%1]
RegEx Details:
\s
: Match a whitespace/+
: Match 1+/
s([^?]*?)
: Lazily match 0 or more of any characters that are not?
. Capture this value in%1
/*
: Match 0 or more trailing/
s[\s?]
: Must be followed by a?
or a whitespace
来源:https://stackoverflow.com/questions/63869599/htaccess-how-to-apply-regex-patterns-on-the-output-of-another-encapsulation