Apache RewriteRule 仅允许白名单 URL

标签 apache mod-rewrite url-rewriting http-status-code-403 whitelist

我有三种不同类别的 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/

相关文章:

html - HTML 中的绝对路径与相对路径 <head>

python - Apache mod_wsgi 和 python 2.7

apache - 如何在我的 ec2 ami apache 服务器上启用 https

php - 在 $_GET 中使用转义 & 符号的 htaccess 重写规则失败

kubernetes - 使用 nginx ingress kubernetes 重写目标问题

apache - tomcat可以配置为apache的代理吗?

apache - 将子文件夹重定向到根目录并将其隐藏在 url 中

css - 在子文件夹中使用 htaccess 从 css 动态加载图像

php - 基于类别名称的 SEO URL 在 URL 中没有类别 ID

php - 将国家代码添加到 Wordpress 中所有 URL 的开头