installation, configuration and optimization of Nginx and PHP (FastCGI)

Source: Internet
Author: User
Tags diff php error php script php source code phpinfo nginx server

First, what is FastCGI
FastCGI is a scalable, high-speed interface for communicating between HTTP server and dynamic scripting languages. Most popular HTTP servers support FASTCGI, including Apache, Nginx, and lighttpd, while FASTCGI is supported by a number of scripting languages, including PHP.
FastCGI is an improvement from the development of CGI. The main disadvantage of the traditional CGI interface approach is poor performance because every time the HTTP server encounters a dynamic program, it needs to restart the script parser to perform the parsing, and the result is returned to the HTTP server. This is almost unusable when dealing with high concurrent accesses. In addition, the traditional CGI interface is also poorly secured, and is now rarely used.
FastCGI interface mode uses the C/s structure, can separate the HTTP server and the script parsing server, and start one or more script parsing daemon on the script parsing server. Each time the HTTP server encounters a dynamic program, it can be delivered directly to the fastcgi process to execute, and the resulting results are returned to the browser. This approach allows the HTTP server to handle static requests exclusively or return the results of the dynamic script server to the client, which greatly improves the performance of the entire application system.

Second, nginx+fastcgi operation principle
Nginx does not support direct invocation or parsing of external programs, and all external programs (including PHP) must be called through the FastCGI interface. The FastCGI interface is a socket under Linux (the socket can be either a file socket or an IP socket). In order to invoke a CGI program, you also need a fastcgi wrapper (wrapper can be understood as the program used to start another program), which is bound to a fixed socket, such as a port or a file socket. When Nginx sends a CGI request to the socket, through the FastCGI interface, wrapper accepts the request and derives a new thread, which invokes the interpreter or the external program to process the script and reads the return data; Wrapper the returned data through the FastCGI interface, along the fixed socket to nginx; Finally, Nginx sends the returned data to the client, which is the whole process of nginx+fastcgi. The detailed procedure is shown in 1.

Figure 1 nginx+fastcgi Operating principle

Third, spawn-fcgi and PHP-FPM

As described earlier, the FastCGI interface method initiates one or more daemons on the script resolution server to parse the dynamic script, which is the FASTCGI process Manager, or the fastcgi engine. SPAWN-FCGI and PHP-FPM are the two fastcgi process managers that support PHP.
The following is a brief introduction of the similarities and differences between spawn-fcgi and PHP-FPM.

SPAWN-FCGI is part of the HTTP server lighttpd, and is now independently a project, typically used in conjunction with LIGHTTPD to support PHP, but ligttpd spwan-fcgi in high concurrent access, There will be a memory leak or even an automatic restart of the fastcgi problem.

Nginx is a lightweight HTTP server, you must rely on third-party fastcgi processor to be able to parse PHP, so the combination of nginx+spawn-fcgi can also implement the parsing of PHP, here is not too much to tell.

PHP-FPM is also a third-party fastcgi process Manager, which is developed as a patch for PHP, it also needs to be compiled with the PHP source code at the time of installation, that is, the PHP-FPM is compiled into the PHP kernel, so the performance of the processing is more excellent And it is also much better at handling high concurrency than the spawn-fcgi engine, so it is recommended that this combination of nginx+php/php-fpm be parsed for PHP.

FastCGI's main advantage is to separate the dynamic language and HTTP server, so nginx and PHP/PHP-FPM are often deployed on different servers to share the pressure of the front-end Nginx server, so that nginx-only processing static requests and forwarding dynamic requests, and PHP /PHP-FPM Server-Exclusive parsing of PHP dynamic requests.

Iv. installation and optimization of PHP and PHP-FPM

1. Download the installation package
Download PHP source package from Www.php.net official website, here is the stable version of php-5.2.13.tar.gz.
Download the corresponding PHP-FPM source package from http://php-fpm.org/downloads/, here is php-5.2.13-fpm-0.5.13.diff.gz.
Be aware that when downloading the package version, try to make PHP and PHP-FPM version consistent, if the version is too large, there can be compatibility issues.

2. Configuring the Installation Environment
Installation of PHP requires the support of the following packages, if not installed, please install them yourself.

    1. GCC gcc-c++ libxml2 libxml2-devel autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel zlib zlib-de Vel glibc glibc-devel glib2 glib2-devel

Due to the uncertainties of each Linux system version, readers can install the corresponding software library according to the error message during the installation of PHP.

3. Start compiling and installing PHP and PHP-FPM
Compiling and installing PHP and PHP-FPM is simple, the following is the installation process:

    1. [[email protected] local] #tar  zxvf php-5.2.13.tar.gz  
    2. [[email protected] local] #gzip  -cd php-5.2.13-fpm-0.5.13.diff.gz |  PATCH -D PHP-5.2.13 -P1  
    3. [[email protected] local] #cd  php-5.2.13  
    4. [[Email protected] php-5.2.13]#./configure  --prefix=/usr/local/php --enable-fastcgi --enable-fpm  
    5. [[ EMAIL PROTECTED] PHP-5.2.13] #make  
    6. [[email protected] php-5.2.13] #make   Install  
    7. [[email protected] php-5.2.13]cp php.ini-dist /usr/local /php/lib/php.ini  

The second step is to add php-fpm as a patch into the PHP source code.
In the "./configure" compilation option, specify that PHP be installed to/usr/local, "--enable-fastcgi" is enabled for PHP fastcgi support, "--ENABLE-FPM" is the activation of FPM support for fastcgi mode.
There are many compile options that can be added when compiling PHP, but there are no more compile options to introduce PHP's fastcgi functionality.

4. Configuration and Optimization php-fpm
The global configuration file for PHP is php.ini, and in the above steps, the file has been copied to/usr/local/php/lib/php.ini. Depending on the needs of each application, the php.ini can be configured accordingly.
The following highlights the configuration files for the PHP-FPM engine.

The default configuration file for PHP-FPM is/usr/local/php/etc/php-fpm.conf, based on the installation path specified above.
PHP-FPM.CONF is an XML-formatted plain text file whose contents are easily understood. Here are a few key configuration tags:

The label listen_address is the IP address and port that the fastcgi process listens on, and the default is 127.0.0.1:9000.
<value name= "Listen_address" >127.0.0.1:9000</value>

The label display_errors is used to set whether to display PHP error message, default is 0, do not display error message, set to 1 can display PHP error message.
<value name= "Display_errors" >0</value>

The tags user and group are used to set up the users and user groups that run the fastcgi process. Note that the users and user groups specified here are consistent with the users and user groups specified in the Nginx configuration file.
<value name= "User" >nobody</value>
<value name= "group" >nobody</value>

Label Max_children The number of processes used to set fastcgi. According to the official recommendation, less than 2GB of memory server, can only open 64 processes, more than 4GB of memory server can open 200 processes.
<value name= "Max_children" >5</value>

The label request_terminate_timeout is used to set the time fastcgi executes the script. The default is 0s, which is infinite execution, and can be modified according to the situation.
<value name= "Request_terminate_timeout" >0s</value>

The label rlimit_files is used to set the PHP-FPM limit on open file descriptors, which is 1024 by default. The value of this tag must be associated with the number of open files in the Linux kernel, for example, to set this value to 65535, you must execute ' ULIMIT-HSN 65536 ' on the Linux command line.
<value name= "Rlimit_files" >1024</value>

The label max_requests indicates how many requests per children are processed and is turned off, with the default setting of 500.
<value name= "Max_requests" >500</value>

The label allowed_clients is used to set the IP address that allows access to the FASTCGI process resolver. If you do not specify an IP address here, the PHP parsing request sent by Nginx will not be accepted.
<value name= "Allowed_clients" >127.0.0.1</value>

5. Managing the FASTCGI process
After you have configured PHP-FPM, you can start the fastcgi process. There are two ways to start the fastcgi process:

    1. /usr/local/php/bin/php-cgi--FPM
    2. Or
    3. /USR/LOCAL/PHP/SBIN/PHP-FPM start

The second way to start the fastcgi process is recommended.
/USR/LOCAL/PHP/SBIN/PHP-FPM also has other parameters, specifically start|stop|quit|restart|reload|logrotate.
Each startup parameter has the following meanings:

    1. ? Start, launch the PHP fastcgi process.
    2. ? Stop, forcing the PHP fastcgi process to terminate.
    3. ? Quit, smooth termination of PHP fastcgi process.
    4. ? Restart, restart the PHP fastcgi process.
    5. ? Reload, reload PHP php.ini.
    6. ? Logrotate, re-enable the log file.

Reload is a very important parameter, it can reload the changed php.ini without interruption of PHP's fastcgi process, so php-fpm can change the PHP settings in fastcgi mode smoothly.


After the fastcgi process starts, its listening IP address and port are also started, and the information can be viewed through PS and netstat.

  1. [Email protected] php]# NETSTAT-ANTL|GREP 9000
  2. TCP 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN
  3. [Email protected] php]# Ps-ef|grep php-cgi
  4. Root 3567 1 0 17:06? 00:00:00/usr/local/php/bin/php-cgi--FPM--fpm-config/usr/local/php/etc/php-fpm.conf
  5. Nobody 3568 3567 0 17:06? 00:00:00/usr/local/php/bin/php-cgi--FPM--fpm-config/usr/local/php/etc/php-fpm.conf
  6. Nobody 3569 3567 0 17:06? 00:00:00/usr/local/php/bin/php-cgi--FPM--fpm-config/usr/local/php/etc/php-fpm.conf
  7. Nobody 3570 3567 0 17:06? 00:00:00/usr/local/php/bin/php-cgi--FPM--fpm-config/usr/local/php/etc/php-fpm.conf
  8. Nobody 3571 3567 0 17:06? 00:00:00/usr/local/php/bin/php-cgi--FPM--fpm-config/usr/local/php/etc/php-fpm.conf
  9. Nobody 3572 3567 0 17:06? 00:00:00/usr/local/php/bin/php-cgi--FPM--fpm-config/usr/local/php/etc/php-fpm.conf
  10. Root 3583 3524 0 17:09 pts/1 00:00:00 grep php-cgi

Five, configure Nginx to support PHP
Nginx installation is particularly simple, the above has been described in detail, here is no longer narrated. The following focus on how Nginx through the PHP-FPM fastcgi process to parse the PHP processing.
Because Nginx itself does not parse PHP, so to implement Nginx support for PHP, in fact, the PHP page request to the FASTCGI process to listen to the IP address and port. If the PHP-FPM as a dynamic application server, then Nginx is actually a reverse proxy server. Nginx through the reverse proxy function to achieve the parsing of PHP, which is the nginx implementation of PHP dynamic parsing principle.
This assumes that the Nginx installation directory is/usr/local, and the path to the Nginx configuration file is/usr/local/nginx/conf/nginx.conf. Below is a virtual host configuration instance that supports PHP parsing under Nginx.

  1. server {
  2. Include port.conf;
  3. server_name www.ixdba.net ixdba.net;
  4. Location/{
  5. Index index.html index.php;
  6. Root/web/www/www.ixdba.net;
  7. }
  8. Location ~ \.php$ {
  9. root HTML;
  10. Fastcgi_pass 127.0.0.1:9000;
  11. Fastcgi_index index.php;
  12. Fastcgi_param Script_filename Html$fastcgi_script_name;
  13. Include Fastcgi_params;
  14. }
  15. }

With the location directive, all PHP-suffix files are handed to 127.0.0.1:9000, where the IP address and port are the IP addresses and ports that the fastcgi process listens to.
The fastcgi_param directive specifies the home directory where the PHP dynamic program is placed, that is, the path specified in the $fastcgi_script_name, which is the/usr/local/nginx/html directory. It is recommended that this directory be consistent with the root directory specified by the Nginx virtual host, but it can also be inconsistent.
The Fastcgi_params file is a parameter configuration file for the fastcgi process, and after installing Nginx, a file is generated by default, which is included in the fastcgi parameter configuration file through the include directive.
Next, start the Nginx service.
/usr/local/nginx/sbin/nginx
So far, nginx+php has been configured to complete.

Six, the test Nginx to PHP parsing function
Here, create a phpinfo.php file under the/usr/local/nginx/html directory, with the following content:
<?php phpinfo ();?>
Then access http://www.ixdba.net/index.html through the browser, by default in the browser display "Welcome to nginx!" Indicates that Nginx is operating normally.
Then access the http://www.ixdba.net/phpinfo.php in the browser, if PHP can parse normally, will appear PHP installation configuration and feature List statistics.

Vii. examples to explain the optimization of fastcgi parameters in Nginx
After the configuration is completed nginx+fastcgi, in order to ensure the high-speed and stable operation of the PHP environment, we need to add some fastcgi optimization instructions. An example of optimization is given below to add the following code to the HTTP level in the Nginx master configuration file.

  1. Fastcgi_cache_path/usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=test:10m inactive=     5m;
  2. Fastcgi_connect_timeout 300;
  3. Fastcgi_send_timeout 300;
  4. Fastcgi_read_timeout 300;
  5. Fastcgi_buffer_size 64k;
  6. Fastcgi_buffers 4 64k;
  7. Fastcgi_busy_buffers_size 128k;
  8. Fastcgi_temp_file_write_size 128k;
  9. Fastcgi_cache TEST;
  10. Fastcgi_cache_valid 302 1h;
  11. Fastcgi_cache_valid 301 1d;
  12. Fastcgi_cache_valid any 1m;

The following is an introduction to the meaning of the above code.
The first line of code is to specify a file path for the fastcgi cache, a directory structure level, a keyword area storage time, and an inactive delete time.
FASTCGI_CONNECT_TIMEOUT Specifies the time-out to connect to the backend fastcgi.
FASTCGI_SEND_TIMEOUT Specifies the time-out for sending requests to fastcgi, which is the time-out for sending requests to fastcgi after two handshake has been completed.
The fastcgi_read_timeout specifies the time-out for receiving a fastcgi answer, which is the time-out for receiving fastcgi answers after two handshakes have been completed.

The fastcgi_buffer_size is used to specify how much buffer is required for the first part of the read fastcgi answer, which indicates that the first part (the answer header) that will use 1 64KB of buffer read answer, can be set to Fastcgi_ The buffers option specifies the buffer size.

Fastcgi_buffers specifies how many and how large buffers are needed locally to buffer the fastcgi response request. If a PHP script produces a page size of 256KB, it is allocated a buffer of 4 64KB to cache, if the page size is greater than 256KB, then the portion greater than 256KB will be cached in the path specified by fastcgi_temp, but this is not a good method, Because the data in memory is processed faster than the hard disk. Generally this value should be the site PHP script generated by the middle of the page size, if most of the site script generated by the page size of 256KB, then you can set this value to "16k", "4 64k" and so on.

The default value for Fastcgi_busy_buffers_size is twice times that of Fastcgi_buffers.

Fastcgi_temp_file_write_size indicates how much data block is used when writing to the cache file, and the default value is twice times that of Fastcgi_buffers.

Fastcgi_cache indicates that the FASTCGI cache is turned on and assigned a name. Enabling caching is useful to reduce the load on the CPU and prevent 502 errors, but opening the cache can also cause many problems, depending on the situation.
Fastcgi_cache_valid, fastcgi is used to specify the cache time for the answer code, the values in the instance indicate that the 200 and 302 responses are cached for one hours, the 301 response cache is 1 days, and the other responses are cached for 1 minutes.

This article is from the "Technical Achievement Dream" blog, please be sure to keep this source http://ixdba.blog.51cto.com/2895551/806622

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.