PHP的FPM,位置嵌套与unnested避免代码执行

有什么优势使用:

location ~ \.php { location ~ \..*/.*\.php$ { return 403; } fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; fastcgi_param DOCUMENT_ROOT $realpath_root; fastcgi_intercept_errors on; } 

相比

 location ~ \..*/.*\.php$ { return 403; } location ~ \.php { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; fastcgi_param DOCUMENT_ROOT $realpath_root; fastcgi_intercept_errors on; } 

我想避免在这里显示的任意代码执行: https : //www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#passing-uncontrolled-requests-to-php

在我简单的浏览器testingdomain/somedir/file.jpg/1.php中,两种方式都返回403 ,但是我仍然不确定这是否是我需要的全部安全性。 另外,如果“performance”有任何差异。

我个人不是你所描述的方法的粉丝,因为如果在.php文件的实际URL中有一个点,你可能会产生误报。

通常有三种方法可以避免指示nginx执行任意文件。 我按照自己喜欢的顺序列出了它们。

#1是configurationPHP的cgi.fix_pathinfo设置为0.这将确保即使有人通过/uploads/avatar32.jpg/index.php的URL,那么PHP将查找该文件,而不是试图帮助“修复“path并执行/uploads/avatar32.jpg 。 如果没有find完整的文件path,将根据您的PHP版本返回错误“无input文件指定”或“主脚本未知”。

#2是有nginxtesting的实际文件的存在,如果没有find然后返回404.然而,这不会工作,如果你使用nginx作为逆向代理/负载均衡器到您的PHP服务器。 你的PHP位置最终会看起来像:

 location ~* \.php$ { try_files $uri =404; fastcgi_pass backend; } 

#3是黑名单的方法,它利用了这个漏洞只有在攻击者可以上传文件到你的服务器的情况下才有效。 因此,举例来说,如果您的用户上传进入/上传/那么你将有专门的位置。

 location /uploads { location ~ \.php$ {return 403;} }