5

我正在使用 nginx 配置一个非常标准的网络服务器。服务器按预期工作,但是,我想了解一个小的配置细节。

我目前的配置是:

index index.html index.htm index.php;

location / {
    try_files $uri $uri/ /index.php?q=$uri;
}

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_index index.php;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
}

使用此配置,如果我访问: http: //myweb.com/wp-content/uploads/2012/10/cropped-bitmap11.png/lol.php我会得到预期的 404。

但是,使用此配置:

try_files $uri =404;

location ~ \.php$ {
    fastcgi_index index.php;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
}

我得到一个“拒绝访问”的空白页面。

为什么结果不一样?

谢谢

4

2 回答 2

15

您可能认为try_files在服务器级别必须为每个请求工作。一点也不。恰恰相反,它只适用于不匹配任何location块的请求。

于 2013-02-21T01:47:27.267 回答
3

简短的回答:从 php5.3.9 开始,php-fpm 不允许 .php 和 .php5 以外的扩展名,因为security.limit_extensions您的请求是对现有 .png 文件的默认值。

长答案:这与 try_files 在位置块内部或外部无关。让我们打破并解释一下:

请求是: http: //myweb.com/wp-content/uploads/2012/10/cropped-bitmap11.png/lol.php

在您的第一个配置上

  • 它与location ~ .php$ { ... }块匹配,因为请求以.php.
  • location中的 try_files $uri =404;指令.php$导致 nginx 返回 404,因为没有名为 $uri 的文件 (=/wp-content/uploads/2012/10/cropped-bitmap11.png/lol.php)
  • location / { ... }块永远不会匹配。只有在没有其他位置块匹配时才匹配。(见http://wiki.nginx.org/HttpCoreModule#location

在你的第二个配置

  • 同样,当请求以 结尾时.php,它与.php$位置块匹配。
  • 在 location 块内没有检查文件是否存在,请求直接传递给 fastcgi 进程。
  • fastcgi 进程找到/wp-content/uploads/2012/10/cropped-bitmap11.png(显然,它存在)并拒绝运行请求,因为 .png 扩展名。(见简短回答)

我不知道这是错误还是“设计”的东西,但与“根”指令相反,位置块之外的 try_files 指令不会在位置块内继承。(如果有错,有人可能会纠正)

于 2013-02-21T01:31:45.310 回答