覆盖nginx中的位置指令不起作用

时间:2015-12-03 10:51:45

标签: nginx

我想覆盖/folder/script.php的权限,并遵守以下规则:

 location ^~ /folder/script.php{
    allow all;
  }              #shouldn't ^this one with ^~ override the others?

 location ~ /folder/(.+)\.php$ {
  deny all;
  return 404;
  allow 127.0.0.1;
 }

  location ~ ^/folder {
    return 404;
  }

location / {

        # First attempt to serve request as file, then
        # as directory, then trigger 404
        try_files $uri $uri/ =404;
        server_name_in_redirect off;        

}

location ~ \.php$ {
        try_files $uri =404;

        #fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

        #fastcgi_pass /tmp/php5-fpm.sock;
        #fastcgi_pass /var/run/php5-fpm.sock;
        fastcgi_pass 127.0.0.1:9000;

           fastcgi_index index.php;  

        fastcgi_param SCRIPT_FILENAME   $root_folder$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $root_folder;

        # send bad requests
        fastcgi_intercept_errors on;

        include fastcgi_params;
    }

但每当我访问admin.php时,我仍然会收到404错误和/或script.php文件被提供下载,而不是解释。有人能解释我为什么吗? Tyvm

1 个答案:

答案 0 :(得分:0)

执行php脚本的命令是:

    try_files $uri =404;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $root_folder$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $root_folder;
    fastcgi_intercept_errors on;
    include fastcgi_params;

我不确定您在哪里定义$root_folder,通常使用$document_root。上述(或类似的)代码必须出现在预期执行php脚本的每个location块中。

所以你的配置应该是这样的:

location / {
  try_files $uri $uri/ =404;
  server_name_in_redirect off;
}

location ^~ /folder { deny all; }

location = /folder/script.php {
    try_files $uri =404;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $root_folder$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $root_folder;
    fastcgi_intercept_errors on;
    include fastcgi_params;
}

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $root_folder$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $root_folder;
    fastcgi_intercept_errors on;
    include fastcgi_params;
}

我冒昧地简化了你的配置。似乎只有文件/folder/script.php/folder层次结构中可执行,因此使用完全匹配(location =),并且/folder被拒绝。 allow 127.0.0.1;之后的deny all无效。

如您所见,fastcgi_pass 127.0.0.1:9000;指令必须出现在直接处理php代码的任何位置容器中。我会将部分或全部这些指令放入一个单独的文件中,并使用include将它们拉入每个位置。

其他指令已经从您的问题中复制过来,但我不知道这里是否需要它们。