Nginx + FastCGI + C抛出502错误的网关

问题描述 投票:1回答:4

我正在尝试使用FASTCgi运行Nginx来通过C应用程序后端处理请求。

我正在使用本教程:http://www.kutukupret.com/2010/08/20/nginx-fastcgi-hello-world-in-c/

我的Nginx配置文件:

server
  {
    listen 80;
    listen [::]:80 default ipv6only=on;

    server_name localhost;

    location /
    {
      fastcgi_pass   127.0.0.1:8000;

      fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
      fastcgi_param  SERVER_SOFTWARE    nginx;
      fastcgi_param  QUERY_STRING       $query_string;
      fastcgi_param  REQUEST_METHOD     $request_method;
      fastcgi_param  CONTENT_TYPE       $content_type;
      fastcgi_param  CONTENT_LENGTH     $content_length;
      fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
      fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
      fastcgi_param  REQUEST_URI        $request_uri;
      fastcgi_param  DOCUMENT_URI       $document_uri;
      fastcgi_param  DOCUMENT_ROOT      $document_root;
      fastcgi_param  SERVER_PROTOCOL    $server_protocol;
      fastcgi_param  REMOTE_ADDR        $remote_addr;
      fastcgi_param  REMOTE_PORT        $remote_port;
      fastcgi_param  SERVER_ADDR        $server_addr;
      fastcgi_param  SERVER_PORT        $server_port;
      fastcgi_param  SERVER_NAME        $server_name;
    }
  }

我的C文件“ hello.c”:

#include <fcgi_stdio.h>
int main( int argc, char *argv[] )
{
   while( FCGI_Accept() >= 0 ) {
      printf( "Content-Type: text/plainnn" );
      printf( "Hello world in Cn" );
   }
   return 0;
}

我使用FastCGI开发套件编译C文件,并生成一个hello二进制文件。

最后运行此行:spawn-fcgi -a 127.0.0.1 -p 8000 -n /var/www/example.com/bin/hello

但是当我放入浏览器http://localhost时,它会抛出“ 502错误的网关”。

有人可以给我带来些光吗?

c nginx fastcgi
4个回答
4
投票
您的printf行有错误-

printf( "Content-Type: text/plainnn" );

应该是-

printf( "Content-Type: text/plain\r\n\r\n" );

注意\r\n\r\n这是HTTP标头和HTTP正文之间的强制性分隔符。

4
投票
我建议您查看nginx错误日志:

sudo tail -f /var/log/nginx/error.log

我遇到了同样的错误,但是使用的是C ++服务器,该服务器使用CppCMS库和unix套接字与nginx进行通信。从错误日志中,我可以看到套接字文件的文件权限存在问题:

2014/05/28 14:52:01 [crit] 1818#0: *172 connect() to unix:/tmp/fcgi-socket failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET /server HTTP/1.1", upstream: "fastcgi://unix:/tmp/fcgi-socket:", host: "localhost:8080"

仅将它们设置为777就为我解决了这个问题。

0
投票
它看起来像您的php5-fpm不在nginx conf中包含的8000端口上运行

fastcgi_pass 127.0.0.1:8000;

您可以使用以下命令来验证您的php5-fpm是否正在该端口上运行

grep -Hr "8000" /etc/php5/fpm/pool.d

对于在8000上安装php5-fpm,请打开以下文件并更改侦听8000端口

vim etc/php5/fpm/pool.d/www.conf

现在搜索收听并用下一行替换它

listen = 127.0.0.1:8000

保存文件并重新启动php5-fpm

0
投票
我遇到了相同的错误,并设置了我的Nginx conf,因为这解决了我的问题:

location / { include fastcgi_params; fastcgi_pass localhost:8000; }

© www.soinside.com 2019 - 2024. All rights reserved.