1.9 NGINX-HTTP configuration optimization - reverse generation of FastCGI (NGINX+PHP)

1.9 HTTP configuration optimization - reverse generation of FastCGI (NGINX+PHP)

As a WEB server, NGINX only has the ability to parse static pages, and the ability to parse dynamic pages can only be realized with the help of external programs (PHP, Tomcat, etc.).
PHP is a PHP parsing platform for running scripts written in PHP language.
NGINX supports to forward requests to FastCGI server through FastCGI interface (client) through FastCGI reverse proxy working mode, and PHP provides a FastCGI connection management extension (PHP-FPM), namely FastCGI server, so we can integrate NGINX and PHP to work together, and NGINX does WEB static page processing, while dynamic PHP requests are Forward it to PHP for work, and realize dynamic and static separation.

1.9.1 RPM installation mode

System version: CentOS Linux release 7.3.1611

1. Configure YUM source
[root@localhost ~]# rpm -i https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
[root@localhost ~]# rpm -i http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
[root@localhost ~]# yum clean all
[root@localhost ~]# yum makecache
2. Install NGINX, PHP and related extensions
[root@localhost ~]# yum -y install nginx php72 php72-php-fpm php72-php-mysqlnd php72-php-pecl-mysql
3. Configure PHP
[root@localhost ~]# vim /etc/opt/remi/php72/php.ini
...
max_execution_time = 30
#The maximum execution time of each PHP script, in seconds.
max_input_time = 60
#Maximum input time, the timeout for PHP to accept requests, in seconds.
memory_limit = 128M
#The maximum memory size a script can use.
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
html_errors = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 8M
#The maximum size of POST data that PHP accepts.
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
default_charset = "UTF-8"
doc_root =
user_dir =
enable_dl = Off
file_uploads = On
upload_max_filesize = 2M
#The maximum file size that PHP allows users to upload.
max_file_uploads = 20
#The maximum number of files that PHP allows to upload at the same time.
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
4. Configure PHP-FPM
[root@localhost ~]# vim /etc/opt/remi/php72/php-fpm.d/www.conf
[www]
user = nginx
#Set the running user to use to run PHP-FPM.
group = nginx
#Set the run user group used to run PHP-FPM.
listen = 127.0.0.1:9000
#Set listening address and port.
listen.allowed_clients = 127.0.0.1
#Set the FastCGI client address allowed to connect.
pm = dynamic
#Set the PHP-FPM process working mode:
# Dynamic dynamic mode: when the number of requests increases, the number of processes will be increased to the maximum limit dynamically, and will be released to the specified end of line automatically when idle.
# In static static mode, you can directly open a specified number of processes without increasing or decreasing.
# On demand mode, when there is a request, the process will be created to work, and when idle, the process will be released.
pm.max_children = 50
#Set the maximum number of processes in PHP-FPM. The maximum number of processes is online in dynamic mode, and the corresponding maximum number of processes is directly opened in static mode.
pm.start_servers = 5
#Set the number of processes started when PHP-FPM starts in dynamic mode.
pm.min_spare_servers = 5
#Set the minimum number of PHP-FPM idle processes allowed to open in dynamic mode.
pm.max_spare_servers = 10
#Set the maximum number of PHP-FPM idle processes allowed to open in dynamic mode.
slowlog = /var/opt/remi/php72/log/php-fpm/www-slow.log
php_flag[display_errors] = on
php_admin_value[error_log] = /var/opt/remi/php72/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path]    = /var/opt/remi/php72/lib/php/session
php_value[soap.wsdl_cache_dir]  = /var/opt/remi/php72/lib/php/wsdlcache
5. Create NGINX + anti generation FastCGI optimization profile

Create the NGINX anti generation FastCGI optimization configuration file of the corresponding project.

[root@localhost ~]# vim /etc/nginx/conf.d/test_fastcgi_optimization.conf
###########################
#==FastCGI Agent related tuning configuration==#
###########################
#Fastcgi related tuning configuration is applicable to NGINX+PHP environment.

fastcgi_connect_timeout 75s;
#Set the timeout in seconds for NGINX to establish a connection with the backend F server. Generally, the time will not exceed 75s.
fastcgi_send_timeout 75s;
#Set the timeout, in seconds, for NGINX to forward requests to the back-end FastCGI server to establish a connection.
fastcgi_read_timeout 75s;
#Set the timeout in seconds for NGINX to read the response from the backend FastCGI server.

fastcgi_keep_conn on;
#Enable NGINX to keep a long connection with the FastCGI server at the back end, and keep a long session connection. When the request comes, it does not need to go through TCP three times
#Hand can improve the communication efficiency between NGINX and the back-end FastCGI server.

#################
#==Request response buffer==#
#################
#Concept of buffer: buffer is a traffic shaping technology used by users to write (send) data in memory, which can reduce the number of response transfers
#Number, improve transmission efficiency. NGINX requests a piece of space in memory as a buffer for buffering the response results from the back-end server when receiving
#After a complete response, it is delivered to the client in one time, avoiding multiple deliveries. The number of responses sent (written) by the backend server (user) to the requesting client
#It is reported that the buffer of NGINX proxy server is used for traffic shaping to improve its transmission efficiency.
fastcgi_request_buffering on;
#Enables buffering from the body of the client request. After buffering is enabled, NGINX will send the entire client before sending the request to the FastCGI server
#The client's complete request is stored in the buffer first, and when the acceptance is completed, the request is forwarded to the FastCGI server at the back end for processing at one time
#High request forwarding efficiency.
fastcgi_buffering on;
#Enables buffering of responses from FastCGI servers. When buffering is enabled, NGINX receives the response from the FastCGI server as soon as possible and saves it
#To the buffer set by the "fastcgi buffer size" and "fastcgi buffers" instructions, if the response is too large to exceed the two instruction settings
#The value of will write the response data to the temporary file on the disk
#Controlled by the "fastcgi ﹣ Max ﹣ temp ﹣ file ﹣ size" and "fastcgi ﹣ temp ﹣ file ﹣ write ﹣ size" instructions, which is not what we expect
#Look at it.
fastcgi_buffer_size 4k;
#Set the buffer size used by NGINX to store the response headers from the back-end FastCGI server. By default, the buffer size
#It's equal to a memory page, 4K or 8K. In general, the response header information will not exceed 1KB, so we can set this value smaller, no
#It depends on the platform. It is suggested to keep the default.
fastcgi_buffers 8 4k;
#Set the size and number of buffers used by NGINX to store the response body from the back-end FastCGI server. Setting this value depends on the
#The size of response data generated by the WEB application of FastCGI server on the end.
fastcgi_busy_buffers_size 8k;
#Set in a high load environment, NGINX does not fully wait for the back-end full response storage
#When you go to the buffer set by the "fastcgi buffer" and "fastcgi buffer size" instructions, NGINX starts to send a ring to the client
#The thread reads the response data stored in the buffer set by this item. This item is mainly used in high load environment
#When the response is not completely stored in the specified buffer, in case of emergency, some response data will be stored in the buffer set by
#The thread reads, and the specified buffer continues to receive response data from the backend. The recommended setting is a "fastcgi_buffers" instruction single buffer
#Twice the size.
fastcgi_max_temp_file_size 1024m;
#Set the maximum size of the temporary file allowed by NGINX to store the response data from the back-end FastCGI server. When the response data exceeds
#The response data will not be written to the temporary file of the disk until the total size of the buffer set by the "fastcti_buffers" instruction is small
#What we expect to see. The default value is 1024m.
fastcgi_temp_file_write_size 8k#Set the size of the data used to limit one write to the temporary file, which is recommended to be the same as the value of "fastcgi \ busy \ buffers \ size".
fastcgi_temp_path /var/lib/nginx/tmp/fastcgi_response 1 2;
#Set the path where temporary files are stored in the disk directory, "1" indicates that the first level directory is named with random 1 character, "2" indicates that the second level directory is named with random 2 words
#Name naming.

#################
#==Response content cache==#
#################
#Note: for the back-end PHP is dynamic data, it is not recommended to use response cache to avoid the inconsistency between the client data caused by cache and the real back-end data.
#Cache Description: cache is to cache the response data of the back end to NGINX, and the request directly matches the returned result of the cache, without any further request forwarding operation,
#It can improve the efficiency of WEB application and reduce the load of back-end host.
#Cache is suitable for static data that does not change frequently, such as picture data, etc. for interactive dynamic data, data that often changes,
#In order to avoid data disorder and ensure data consistency, it is recommended not to use.
#fastcgi_cache one;
#When FastCGI cache is enabled, NGINX will cache the response content of the back-end WEB server to the local disk to improve the data processing efficiency. "one" means tone
#Reverse the FastCGI response content cache defined in the "http {}" block.
#fastcgi_cache_valid 200 302 10m;
#Set the effective time of the corresponding response code content cache. 10 minutes.
#fastcgi_cache_valid 301 1d;
#Set the effective time of the corresponding response code content cache. 1 days.
#fastcgi_cache_valid any 1m;
#Set the effective time of the corresponding response code content cache. 1 minutes.
6. Configure NGINX
[root@localhost ~]# vim /etc/nginx/nginx.conf
....
#############
#==Core configuration==#
#############
http {
....Omitted. For other configurations, please refer to< HTTP Basic configuration optimization.
################################
#==Counter generation FastCGI Response content cache==#
################################
fastcgi_cache_path /tmp/nginx/cache levels=1:2 keys_zone=one:10m max_size=200m inactive=60;
#Set a response content cache to cache the response data of the back-end FastCGI server to the local to improve the transmission efficiency.
# level=1:2 sets the cache directory level, "1" indicates that the first level directory is named with one character, "2" indicates that the second level directory is named with two words
#                    Name naming.
# Key_zones = one: 10 m sets the name and size of the metadata storage space, "one" indicates that the cache space name can be modified, "10 m" indicates this
#                    The initial size of the cache space.
# max_size=200m set the maximum size of the disk space occupied by the cache, in MB. If not set, the cache may occupy the entire disk
#                    Space.
# inactive=60 sets the retention time of the cache file in the cache space that is not accessed, in minutes. When the time is exceeded, the cache will
#                    Is automatically deleted.

    ################
    #==WEB Site configuration==#
    ################
    server {
        server_name  www.test.com;
        listen 80;
        access_log  /var/log/nginx/test.access.log main;

        location / {
            root /usr/share/nginx/html;
            index index.html;
            try_files $uri $uri/ /index.php?s=$uri&$args;
            #When users access, they first find a directory. If there is a WEB page in the directory, it will be displayed. If there is no directory, they will continue to find the next directory
            #If there are any directories, the URI will be redirected to the URI path recognized by PHP, which will be matched by the URI defined by the Location below
            #To, present dynamic page, realize dynamic and static combination.
        }

        location ~ ^.*\.(php|php5)?$ {
                fastcgi_pass 127.0.0.1:9000;
                #Set the backend FastCGI host to proxy.
                fastcgi_index index.php;
                #The settings tell the FastCGI server that PHP applies the default entry file name.
                fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
                #Setting tells FastCGI server that the directory path of PHP application is equivalent to the root directory defined by the "root" instruction above.
                include fastcgi.conf;
                #The settings include other configuration files, which are defined in fastcgi.conf configuration file to tell the FastCGI service
                #In general, we don't need to change the content of the default option parameter of the.
                include /etc/nginx/conf.d/test_fastcgi_optimization.conf;
                #Set the other profiles included and call the optimization profile defined above.
        }

        error_page 404 /404.html;
        location = /40x.html {
        }

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

We create a test static page (index.html) and a test dynamic page (index.php)

[root@localhost ~]# vim /usr/share/nginx/html/index.html
hello world!
[root@localhost ~]# vim /usr/share/nginx/html/index.php
<?php
phpinfo();
?>
8. Running NGINX and PHP-FPM services
[root@localhost ~]# systemctl start php72-php-fpm
[root@localhost ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost ~]# nginx
[root@localhost ~]# netstat -lnupt |grep nginx
tcp        0      0 0.0.0.0:80      0.0.0.0:*     LISTEN      1629/nginx: master  
[root@localhost ~]# netstat -lnupt |grep php-fpm
tcp        0      0 127.0.0.1:9000  0.0.0.0:*     LISTEN      1659/php-fpm: maste 
9. Access test

Enter the default address (shorter URL) to render the static WEB homepage! Entering the address with suffix (long URL) will render the dynamic PHP information page!

Tags: Nginx PHP vim RPM

Posted on Mon, 06 Jan 2020 16:24:53 -0800 by stereo