【问题标题】:Apache RewriteCond equivalent in NginxNginx 中的 Apache RewriteCond 等价物
【发布时间】:2023-04-01 01:29:01
【问题描述】:

我是 Nginx 的新手,并试图将我为 WordPress 网站的以下规则从 Apache 转换为 Nginx。我从运行 Nginx 1.4.6 的 Ubuntu 机器上的默认 Nginx 配置开始。

RewriteCond %{REQUEST_URI} !^/wp-content/themes/path/to/exclude/file\.php
RewriteRule wp-content/themes/(.*\.php)$ log.php?f=$1 [L]

上述规则将所有对wp-content/themes/*.php 的请求重写为security-log.phpRewriteCond 规则中定义的文件除外。

据我所知,在 Nginx 中执行此操作的方法是使用 location 块。我尝试了以下方法(我仍然不确定如何排除特定文件/文件夹)。

location = /wp-content/plugins/(.*\.php)$ {
    try_files /security-log.php =404;
}

上面的规则似乎被完全忽略了(也许我的正则表达式有问题?)。

如果我提供一个固定路径,如下所示,规则被调用,但 Nginx 将提供 PHP 文件(浏览器将下载文件)而不是使用 PHP 解释器执行它(很可能这是因为 fast-cgi 是没有被召唤)。

location = /wp-content/plugins/test.php {
    try_files /security-log.php =404;
}

实现这一目标的最佳方法是什么?

【问题讨论】:

标签: php wordpress nginx nginx-location


【解决方案1】:

您的第一次尝试对于正则表达式位置的语法无效。它应该看起来像这样:

location ~ ^/wp-content/plugins/.*\.php$ { ... }

您应该使用rewrite,而不是try_files 指令,如下所示:

rewrite ^ /security-log.php last;

当然,这两种方法都不匹配.htaccess文件的功能。

您已经观察到处理 PHP 文件的位置块必须包含 fastcgi 指令。这可以通过将它们放入单独的文件并使用include 指令将它们拉入多个location 块中来实现。

这意味着.htaccess 文件可以通过在现有location ~ \.php$ 块之前放置一个正则表达式位置来实现。例如:

location = /wp-content/themes/path/to/exclude/file.php {
    include common-php-directives;
}
location ~ ^/wp-content/themes/.*\.php$ {
    rewrite ^/wp-content/themes/(.*\.php)$ /log.php?f=$1 last;
}
location ~ \.php$ {
    include common-php-directives;
}

有关位置语法,请参阅this document

【讨论】:

  • 第二条规则有效,但是,排除似乎不起作用。我的猜测是 Nginx 在第一条规则之前优先考虑第二条规则。
  • Regex 位置被排序,以便第一个匹配的位置获胜。糟糕,但在完全匹配的位置有错字 - . 不应转义。
【解决方案2】:

我可以推荐你作为 nginx https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/ 的新用户阅读这个陷阱文档

对于 wordpress 设置: https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 2016-07-09
    • 2013-01-14
    • 1970-01-01
    相关资源
    最近更新 更多