從零搭建LNMP環境(二) - 整合Nginx與PHP

管宜堯發表於2015-01-04

安裝Nginx的方式有很多種,這裡我們還是編譯原始碼進行安裝,使用下列命令:

$ wget http://nginx.org/download/nginx-1.6.2.tar.gz
$ tar -zxvf nginx-1.6.2.tar.gz
$ cd nginx-1.6.2
$ ./configure --prefix=/usr/local/nginx
$ make
$ sudo make install

如果安裝過程中出現如下錯誤

./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.

則需要先安裝pcre

$ sudo yum install pcre-devel

安裝完成之後,我們的Nginx安裝目錄在/usr/local/nginx。 接下來修改nginx的配置檔案(/usr/local/nginx/conf/nginx.conf),使其能夠處理php指令碼。

worker_processes  1;

events {
  worker_connections  1024;
}
http {
  include       mime.types;
  default_type  application/octet-stream;
  sendfile        on;
  keepalive_timeout  65;
  server {
    listen       80;
    server_name  _;
    root /vagrant;

    location / {
      index  index.html index.htm index.php;
    }

    location /demo {
      index index.php;
      if (!-e $request_filename) {
          rewrite ^/demo/(.*)$ /demo/index.php?$1 last;
          break;
      }
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }

    location ~ \.php$ {
      fastcgi_pass   127.0.0.1:9000;
      fastcgi_index  index.php;
      fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
      include        fastcgi_params;
    }
  }
}

最後,啟動Nginx時,需要先啟動PHP-FPM。

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

對於Nginx的重啟以及關閉操作,可以使用以下命令

$ sudo /usr/local/nginx/sbin/nginx -s [reload|restart|stop]

而PHP-FPM,則麻煩一點,需要先使用ps -ef|grep php-fpm獲取master process的程式ID, 再使用kill -USR2:

$ ps -ef|grep php-fpm

root      6221     1  0 02:17 ?        00:00:00 php-fpm: master process (/usr/local/php/etc/php-fpm.conf)
nobody    6222  6221  0 02:17 ?        00:00:00 php-fpm: pool www
nobody    6223  6221  0 02:17 ?        00:00:00 php-fpm: pool www
vagrant   6233  1623  0 02:18 pts/0    00:00:00 grep php-fpm

$ sudo kill -USR2 6221

注意: -USR2引數為重啟,-INT引數為關閉。

相關文章