问题原文
原帖链接 · John · CC BY-SA 4.0
I have the following rule in my .htaccess file:
RewriteRule ^[^/].*/(dir1|dir2|dir3)(.+) $1$2 [QSA]
It works great for the directories except sometimes it conflicts with files.
How can I modify this rule to immediately require a / after each directory name so that it only matches directories and not files?
Here are some of the things I've tried without success:
RewriteRule ^[^/].*/(dir1|dir2\/|dir3)(.+) $1$2 [QSA]RewriteRule ^[^/].*/(dir1|dir2|dir3)(\/(.+) $1$2 [QSA]RewriteRule ^[^/].*/(dir1|dir2|dir3)(\/.+) $1$2 [QSA]
Example: im/ should match however immortal.woff2 should not.
已采纳解答
原帖链接 · MrWhite · CC BY-SA 4.0
RewriteRule ^[^/].*/(dir1|dir2|dir3)(\/.+) $1$2 [QSA]
This would potentially do as you require, however, this does not match your example im/ (or rather <something>/im/ where im is one of dir1, dir2, or dir3), it would only match <something>/im/<something> due to the + (1 or more) quantifier in the last capturing subgroup. To match <something>/im/ you should change the last quantifier to * (0 or more) instead.
Other (not so) minor points...
- You do not need to backslash-escape literal slashes in Apache regex since spaces are the regex delimiters, so slashes carry no special meaning here.
- The
QSAflag is not required here, since the query string is passed through by default (when a query string is omitted from the substitution string). - The first part of the regex, ie.
^[^/].*/, looks incorrect. This matches a non-slash character, followed by anything (including other slashes), followed by a slash. However, in a directory context (like.htaccess) the first character is never a slash, so the[^/]part is redundant. However, it looks like the dot is erroneous. It looks like the intention is to match a single path segment, eg.foo/dir1/, but the current regex would also matchfoo/bar/baz/dir1/- potentially creating a duplicate content issue (since the resulting rewrite is the same). To match a single path segment only then the first part of the regex should be^[^/]+/instead. Note the+(1 or more) quantifier applies to the non-slash character class. I used+as opposed to*since there will always be at least 1 character before the slash (as mentioned above, the first character is never a slash). This is of course assuming theRewriteRuledirective is being applied to the requested URL and not the output of an earlier rewrite. - You have omitted the
Lflag - are you performing additional rewrites on the output of this rule? Otherwise, theLflag should be included, at the very least to prevent additional (unnecessary) processing, or to prevent undesirable rewrites/redirects.
Bringing the above points together, try the following instead:
RewriteRule ^[^/]+/(dir1|dir2|dir3)(/.*) $1$2 [L]
The purpose of this rule being to remove the first URL-path segment before a selection of known directories (or path segments) via an internal rewrite.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
