實現LNMP環境搭建。
開始安裝Nginx和PHP-FPM之前,首先卸載系統中以前安裝的Apache和PHP保證安裝不會沖突。用root登錄輸入下面的命令:
- yum remve httpd* php*
增加額外資源庫
默認情況下,CentOS的官方資源是沒有php-fpm的, 但我們可以從Remi的RPM資源中獲得,它依賴於EPEL資源。我們可以這樣增加兩個資源庫:
1:安裝nginx:
- yum install nginx
安裝完成后可以啟動nginx,在瀏覽器里面訪問,查看nginx是否安裝成功。端口默認為80。
- systemctl start nginx
- nginx中yum安裝的默認網站根目錄在/usr/share/nginx/html
結果如下:
表示已成功安裝nginx.
2:安裝PHP和PHP-FPM:
- yum install php php-fpm
- 啟動php-fpm
- systemctl start php-fpm
3:將PHP與mysql模塊關聯起來:
- 可以通過yum install mariadh mariadb-server 安裝
- yum install php-gd php-mysql php-mbstring php-xml php-mcrypt php-imap php-odbc php-pear php -xmlrpc
4:配置nginx與php一起工作:
Nginx+FastCGI運行原理
Nginx不支持對外部程序的直接調用或者解析,所有的外部程序(包括PHP)必須通過FastCGI接口來調用。FastCGI接口在Linux下是socket,(這個socket可以是文件socket,也可以是ip socket)。為了調用CGI程序,還需要一個FastCGI的wrapper(wrapper可以理解為用於啟動另一個程序的程序),這個wrapper綁定在某個固定socket上,如端口或者文件socket。當Nginx將CGI請求發送給這個socket的時候,通過FastCGI接口,wrapper接納到請求,然后派生出一個新的線程,這個線程調用解釋器或者外部程序處理腳本並讀取返回數據;接着,wrapper再將返回的數據通過FastCGI接口,沿着固定的socket傳遞給Nginx;最后,Nginx將返回的數據發送給客戶端,這就是Nginx+FastCGI的整個運作過程。詳細的過程,如下圖所示:
打開nginx主配置文件。
vim /etc/nginx/nginx.conf
- 在http模塊中添加配置:
- location / {
- root /usr/share/nginx/html;
- index index.html index.htm index.php;
- }
- 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;
- }
5:測試nginx與php是否正常。
重啟nginx服務器,在網站根目錄創建一個index.php文件
- # vi /usr/share/nginx/html/info.php
文件內容如下:
- <?php
- phpinfo();
- ?>
可以看到我們的php文件可以加載出來了。此時我們的nginx已經與php關聯可以共同工作了。即LNMP環境搭建完畢。