kankacan一、FastCGI特点:

1、HTTP服务器和动态脚本语言间通信的接口或工具

2、可把动态语言解析和HTTP服务器分离I

3、Nginx、Apache、Lighttpd,以及多数动态语言 都支持FastCGI

4、FastCGI接口方式采用 C/S结构,分为客户端(HTTP服务器)和服务器端(动态语言解析服务器)

5、PHP动态语言服务器可以启动多个FastCGI的守护进程(例如php-fpm(fcgi process mangement))

6、HTTP服务器通过 FastCGI客户端(Nginx fastcgi_pass)和 动态语言FastCGI服务器(php-fpm) 通信

二、FastCGI原理:

FastCGI接口在Linux下是socket。wrapper 用于启动另一个程序,绑定在某个固定的socket上,如端口或文件socket。调用CGI程序

1、Nginx将CGI请求发送给绑定有wrapper的socket时,通过FastCGI接口,wrapper接收到请求,然后派生出一个新的线程,这个线程调用解释器 或者 外部程序 处理脚本 来读取返回的数据。

2、wrapper再将返回的数据通过FastCGI接口,沿着固定的socket传给Nginx

3、Nginx将返回的数据发送给客户端n 


三、nginx与php-fpm两种通信方式

    unix socket方式要比tcp的方式快,而且消耗资源少,因为socket之间在nginx和php-fpm的进程之间通信,而tcp需要经过本地回环驱动,还要申请临时端口和tcp相关资源。

    unix socket会显得不是那么稳定,当并发连接数爆发时,会产生大量的长时缓存,在没有面向连接协议支撑的情况下,大数据包很有可能就直接出错并不会返回异常。而TCP这样的面向连接的协议,多少可以保证通信的正确性和完整性。


1、tcp方式


#PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
location ~ \.php$ {
      root /root;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      include fastcgi_params;

}

location ~ \.php$ {
      root /root;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      include fastcgi.conf;

}
 tips:diff  fastcgi.conf  fastcgi_params
       fastcgi.conf多了一行fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;


2、unix socket方式


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

# # With php5-cgi alone:
    # fastcgi_pass 127.0.0.1:9000;
       fastcgi_pass unix:/var/run/php5-fpm.sock;
       fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/www/nginx-default$fastcgi_script_name;

# # With php5-fpm:
    # fastcgi_pass unix:/var/run/php5-fpm.sock;
       fastcgi_index index.php;
       include fastcgi_params;

}

tips:修改nginx配置文件location ~ \.php$ 区段之后,记得修改/etc/php5/fpm/pool.d/www.conf 的  listen = 127.0.0.1:9000  或者 listen = unix:/var/run/php5-fpm.sock


参考文档:

oldboy blog
http://xieminis.me/?p=216