去掉 php-fpm 烦人的 “FastCGI sent in stderr: "Primary script unknown"” 错误

陪她去流浪 桃子 2015年7月4日

对 nginx 的使用不熟悉,使用了以下方式来把 php 脚本转交给 php-fpm 处理:

location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
}

但这样有一个问题,就是在当 php 脚本文件不存在时会导致 php-fpm 生成一条错误到 nginx 的日志中,内容如下:

FastCGI sent in stderr: "Primary script unknown"

总有叼民想害朕。老是有人尝试猜测我博客的后台(我博客开源的啊!!),经常尝试各种登录程序,比如『/wp-admin/wp-login.php』等等等等。文件根本不存在,所以导致一堆的『FastCGI sent in stderr: "Primary script unknown"』错误,烦死了。

可用以下办法解决:

location ~ \.php$ {
        try_files      $uri =404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
}

注意到加入了一行try_files $uri =404;,由于 try_files 阶段(phase)先于 fastcgi_pass 执行,所以可以在把处理转交给 fpm 之前进行文件不存在的处理。

参考

发表于:2015年7月4日 ,阅读量:14820 ,标签:nginx · php · FPM

如果文章有帮助到你,请我喝杯冰可乐吧~