【问题标题】:Nginx: try_files outside locationNginx:try_files 外部位置
【发布时间】:2012-10-19 18:03:50
【问题描述】:

我正在使用 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;
}

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

为什么结果不一样?

谢谢

【问题讨论】:

    标签: configuration nginx


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      short anwser: 从 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 结尾。
      • try_files $uri =404; 位置内的 try_files $uri =404; 指令导致 nginx 返回 404,因为没有名为 $uri 的文件 (=/wp-content/uploads/2012/10/cropped-bitmap11.png/lol.php)李>
      • location / { ... } 块永远不会匹配。只有在没有其他位置块匹配时才匹配。 (见http://wiki.nginx.org/HttpCoreModule#location

      关于您的第二个配置

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

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

      【讨论】:

      • a try_files directive outside the location blocks does not inherited inside the location block 我认为这是关键点。如果这是正确的,那么一切都有意义
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 2014-08-18
      • 2018-09-17
      相关资源
      最近更新 更多