Apache RewriteRule 只允许白名单 URL

Apache RewriteRule to only allow whitelist URLs

我有三个不同类别的 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 的表达式中被禁止。我明白为什么会这样,但我不确定如何解决这个问题。我可能在这里遗漏了一些东西,有人可以告诉我应该如何解决这个问题吗?

您应该先定义白名单,然后 restrict/forbid 其他一切:

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]