【问题标题】:Returning 404 for a specific URL in nginx为 nginx 中的特定 URL 返回 404
【发布时间】:2019-12-28 03:59:52
【问题描述】:
location ~* ajax.php {
    if ($args ~ "action=query_new") {
        return 404;
    }
}

我有一个 ajax.php 文件存储在站点 example.com 的测试目录中,我想为所有来自 ajax.php 的请求返回 404 错误,其中包含 args/query 字符串 action=query_new。我写了上面的代码。该代码有效,但它使 ajax.php 文件无法使用,即当上述代码运行时,ajax.php 未执行。我的站点使用此文件来处理其他一些查询字符串。我该如何解决这个问题?

【问题讨论】:

    标签: php ajax nginx


    【解决方案1】:

    在您的nginx 配置中的某个位置,您将有一个类似于location ~ [^/]\.php(/|$) { ... } 或简单的location ~ \.php$ { ... } 的位置块。这包含将 php 文件发送到上游解释器所需的代码。

    您的新位置块优先,并防止任何匹配 ajax.php 的文件作为 php 执行。

    一种解决方案是将发送 php 文件到上游解释器所需的代码复制到 both 位置块中。这可以通过将这些指令移动到单独的文件并使用include 指令将它们加载到每个块中来实现。比如:

    location ~* ajax.php$ {
      if ($arg_action = "query_new") { return 404; }
      include path/to/my_php_config;
    }
    location ~* \.php$ {
      include path/to/my_php_config;
    }
    

    include 指令是documented here

    【讨论】:

    • 你的意思是我添加到位置 ~* \.php$ 我的配置文件块的代码应该移动到位置 ~* ajax.php$ 块? nginx不会报重复代码吗?
    • @Pramod 它应该被复制 - 是的。 nginx 不关心多个位置块是否包含相同的指令。
    • 我会尽快尝试这个策略,并会告诉你结果。谢谢
    猜你喜欢
    • 2015-06-12
    • 2013-06-03
    • 1970-01-01
    • 2013-11-04
    • 2022-12-05
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多