Nginx與PHP(FastCGI)的安裝、配置與優化


FastCGI的介紹和工作原理

  首先簡單的介紹下FastCGI:

  FastCGI是語言無關的、可伸縮結構的CGI開放擴展,其主要行為是將CGI解釋器進行保持在內存中並因此獲得較高的性能。眾所周知,CGI解釋器的反復加載是CGI性能低下的主要原因,如果CGI解釋器保持在內存中並接受FastCGI進程管理器調度,則可以提供良好的性能、伸縮性、Fail-Over特性等。

  FastCGI的工作原理是:

  (1)FastCGI進程管理器自身初始化,啟動多個CGI解釋器進程(多個php-cgi進程)並等待來自Web Server的連接。在文本中,采用PHP-FPM進程管理器啟動多個php-cgi FastCGI進程。啟動php-cgi FastCGI進程時,可以配置以TCP和UNIX套接字兩種方式啟動。

  (2)當客戶端請求達到Web服務器(Nginx)時,Web服務器將請求采用TCP協議或UNIX套接字方式轉發到FastCGI主進程,FastCGI主進程選擇並連接到一個CGI解釋器(子進程)。Web服務器將CGI環境變量和標准輸入發送到FastCGI子進程php-cgi。

  (3)FastCGI子進程完成處理后將標准輸出和錯誤信息從同一連接返回Web服務器(Nginx)。當FastCGI子進程關閉連接時,請求便告知處理完成。FastCGI子進程接着等待並處理來自FastCGI進程管理的下一個連接。而在一般的普通CGI模式中,php-cgi在此便退出了。

PHP-FPM

  PHP-FPM是一個PHP FastCGI管理器,是只用於PHP的,可以在 http://cn2.php.net/downloads.php下載得到.PHP-FPM其實是PHP源代碼的一個補丁,旨在將FastCGI進程管理整合進PHP包中。必須將它patch到你的PHP源代碼中,在編譯安裝PHP后才可以使用。

  新版PHP已經集成php-fpm了,不再是第三方的包了,推薦使用。PHP-FPM提供了更好的PHP進程管理方式,可以有效控制內存和進程、可以平滑重載PHP配置,比spawn-fcgi具有更多優點,所以被PHP官方收錄了。在./configure的時候帶 –enable-fpm參數即可開啟PHP-FPM,其它參數都是配置php的,具體選項含義可以查看這里

  安裝前准備:

yum -y install gcc automake autoconf libtool make

yum -y install gcc gcc-c++ glibc

yum -y install libmcrypt-devel mhash-devel libxslt-devel \
libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel \
zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel \
ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel \
krb5 krb5-devel libidn libidn-devel openssl openssl-devel

  新版php-fpm安裝(推薦安裝方式)

wget http://us1.php.net/get/php-5.5.10.tar.gz/from/this/mirror
tar zvxf php-5.5.10.tar.gz
cd php-5.5.10
./configure --prefix=/usr/local/php  --enable-fpm --with-mcrypt \
--enable-mbstring --disable-pdo --with-curl --disable-debug  --disable-rpath \
--enable-inline-optimization --with-bz2  --with-zlib --enable-sockets \
--enable-sysvsem --enable-sysvshm --enable-pcntl --enable-mbregex \
--with-mhash --enable-zip --with-pcre-regex --with-mysql --with-mysqli \
--with-gd --with-jpeg-dir

make all install

  完成php-fpm后,對其運行用戶進行配置:

cd /usr/local/php
cp etc/php-fpm.conf.default etc/php-fpm.conf
vi etc/php-fpm.conf

修改:
user = nginx
group = nginx

如果nginx用戶不存在,那么先添加nginx用戶
groupadd nginx
useradd -g nginx nginx

  修改nginx配置文件以支持php-fpm

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
    root html;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

  創建測試php文件

  在/usr/local/nginx/html下創建index.php文件,輸入如下內容

<?php
    echo phpinfo();
?>

  啟動php-fpm和nginx

/usr/local/php/sbin/php-fpm 
/usr/local/nginx/nginx

  訪問http://你的服務器ip/index.php,皆可以見到php信息了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM