我有三种不同类别的 URL。每个类别都有一组我想要允许的特定 URL,而其他所有内容都应该被禁止。这是为了锁定我的网站。
这些是我想出的类别和正则表达式。 我正在使用 Apache 2.4。
第一类:
http://example.org/foo
http://example.org/foo/bar
http://example.org/user
^/foo(/bar)?|user$
第二类:
http://example.org/baz/1?foo=bar
^/baz/[0-9]+\?foo=bar$
第三类:
http://example.org/search?bar=baz
^/search\?bar=baz$
以下是我根据上述内容想出的重写规则:
RewriteEngine On
# Category 1
RewriteCond %{REQUEST_URI} !^/foo(/bar)?|user$ [NC]
RewriteRule ^(.*)$ - [F]
# Category 2
RewriteCond %{REQUEST_URI} !^/baz/[0-9]+$ [NC]
RewriteCond %{QUERY_STRING} !^foo=bar$
RewriteRule ^(.*)$ - [F]
# Category 3
RewriteCond %{REQUEST_URI} !^/search$ [NC]
RewriteCond %{QUERY_STRING} !^b=bar$
RewriteRule ^(.*)$ - [F,L]
正则表达式对我来说看起来不错,但当我在 http://htaccess.madewithlove.be/ 测试它们时,我注意到 URL http://example.org/foo
将在类别 2 的表达式中被禁止。我理解为什么会发生这种情况,但我不确定如何解决此问题。我可能在这里遗漏了一些东西,有人可以告诉我应该如何解决这个问题吗?
最佳答案
您应该首先定义白名单,然后限制/禁止其他一切:
RewriteEngine On
RewriteRule ^(?:foo(?:/bar)?|user)/?$ - [L]
RewriteCond %{QUERY_STRING} ^foo=bar$
RewriteRule ^baz/\d+$ - [L]
RewriteCond %{QUERY_STRING} ^b=bar$
RewriteRule ^search$ - [L]
RewriteRule ^ - [F,L]
关于Apache RewriteRule 仅允许白名单 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35577057/