1. 程式人生 > 實用技巧 >nginx如何解析php?

nginx如何解析php?

nginx本身不支援對外部程式的直接呼叫或者解析,所有的外部程式包括php必須通過FastCGI介面來呼叫(FastCGI介面在Linux下是socket)
為了呼叫CGI程式,還需要FastCGI的wrapper,當nginx將cgi請求傳送給這個socket的時候,通過fastcgi介面,wrapper接收到請求,然後派生出一個執行緒,這個執行緒呼叫外部程式處理並返回資料;
接著,wrapper再將返回的資料通過fastcgi介面,socket傳遞給nginx;
最後,nginx將返回的資料傳送給客戶端

一、Nginx解析PHP

PHP-FRM是管理FastCGI的一個管理器

1.php-frm自身初始化,啟動程序php-frm,監聽9000埠;FastCGI子程序等待來自web伺服器的連線

2.當客戶端request到達nginx時,nginx通過location指令,將所有以.php結尾的檔案都交給127.0.0.1:9000(本地php解析伺服器)進行處理

        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;  #表示nginx通過fastcgi_pass將使用者請求的資源發給9000埠進行解析
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;  #指令碼檔案請求的路徑
            include        fastcgi.conf;  #表示nginx會呼叫fastcgi.conf這個配置檔案
        }

ngx_http_fastcgi_module

3.nginx將請求fastcgi客戶端,通過fastcgi_pass將使用者的請求傳送給php-fpm

4.wrapper收到php-fpm的請求後,會生成一個新的執行緒呼叫php動態程式解析伺服器(如果請求是mysql資料的讀取,將會觸發讀庫操作,如果是圖片、檔案等,將會觸發查詢後端儲存伺服器)

5.php將查詢到的結果通過fastcgi返回給nginx

6.nginx將資料返回給使用者

二、如何配置nginx支援php

1.在編譯安裝時新增--enable-fpm 引數即可開啟php-fpm

./configure --prefix=/usr/local/php/  …… --enable-fpm

2.生成php-fpm的配置檔案,並修改引數

#cd /usr/local/php/etc/
cp -a php-fpm.conf.default php-fpm.conf
#vim php-fpm.conf
pid = run/php-fpm.pid
#取消註釋
user = nginx
group = nginx
pm.start_servers = 2
#啟動時開啟的程序數(預設值)
pm.min_spare_servers = 1
#最少空閒程序數(預設值)
pm.max_spare_servers = 3
#最多空閒程序數(預設值)

2.修改nginx的配置檔案,使其識別.php字尾的

#vim /usr/local/nginx/conf/nginx.conf
#取消以下幾行的註釋,並修改include選項的字尾位fastcgi.conf
#65行-71行
        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi.conf;
        }