php environment setup (correct configuration of nginx and php)

1. Nginx realizes the principle of php dynamic analysis

nginx is a high-performance http server and reverse proxy server. That is, nginx can be used as an HTTP server for website publishing, or as a reverse proxy server for load balancing. But it should be noted that: nginx itself does not parse php files. Requests for PHP pages will be handed over by nginx to the IP address and port monitored by the FastCGI process, which will be processed by php-fpm (a third-party fastcgi process manager) as a dynamic analysis server, and finally the processing results will be returned to nginx. That is, nginx transfers dynamic requests to the back-end php-fpm through the reverse proxy function, so as to realize the parsing support for PHP. This is the basic principle of Nginx to achieve PHP dynamic parsing. 

 

First, you need to understand some concepts. (Nginx + php-fpm +fastcgi)

  • Nginx is a 非阻塞IO & IO复用model. Through the epoll-like function provided by the operating system, multiple client requests can be processed in one thread. Nginx processes are threads, that is, there is only one thread in each process, but this thread can serve multiple clients.

  • PHP-FPM is a blocking single-threaded model. It pm.max_children specifies the maximum number of processes and pm.max_requests specifies how many requests each process handles and restarts (because PHP occasionally has memory leaks, it needs to be restarted). Each process of PHP-FPM has only one thread, but a process can only serve one client at a time.

  • fastCGI: In order to solve the communication between different language interpreters (such as php and python interpreters) and webserver, the cgi protocol appeared. As long as you write programs in accordance with the cgi protocol, the language interpreter can communicate with webwerver. Such as php-cgi program. But every time the webserver receives a request, it will fork a cgi process, and then kill the process after the request ends. If there are 10,000 requests, fork and kill the php-cgi process 10,000 times. fastcgi is an improved version of cgi. Fast-cgi will not kill the process every time after processing the request, but keep the process so that it can handle multiple requests at once. Greatly improve efficiency.

Supplement: Relevant knowledge of reverse proxy and forward proxy (in short, forward proxy-proxy is the client; reverse proxy-proxy is the server)

The purpose of the forward proxy:
                (1) Access to previously inaccessible resources, such as Google
                (2) It can be cached to speed up access to resources
                (3) Client access authorization, and Internet access is authenticated
                (4) The proxy can record user access records online Behavior management, hide user information from the outside)

The purpose of reverse proxy: reverse proxy, "it proxy is the server", mainly used in the case of distributed deployment of server clusters, reverse proxy hides server information.
               (1) To ensure the security of the internal network, the reverse proxy is usually used as the public network access address, and the web server is the internal network.
               (2) Load balancing is used to optimize the load of the website through the reverse proxy server

2. How to configure nginx to implement php dynamic analysis by nginx

1. Understand the common sense of nginx configuration (nginx.conf)

The composition of nginx.conf and the basic configuration grammar are explained in another article. Here we will briefly introduce several grammars used in parsing PHP configuration:

2.nginx parsing php configuration example

server {listen       8000 backlog=4096;server_name  www.baidu.com localhost;access_log logs/access.log main;root   /home/leimengyao/api/app/htdocs;location / {index  index.php index.html index.htm;try_files $uri $uri/ /index.php?$args;}location ~ \.php$ {#fastcgi_pass   127.0.0.1:9000;fastcgi_pass unix:/home/leimengyao/php7/var/run/php-fpm.sock;fastcgi_index  index.php;fastcgi_param  SCRIPT_FILENAME  /home/leimengyao/api/app/htdocs$fastcgi_script_name;include        fastcgi_params;}error_page  404              /404.html;location = /404.html {root   /usr/share/nginx/html;}# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   /usr/share/nginx/html;}location ~ /\.ht {deny  all;}}

As configured above, when an http request comes, the processing process is as follows:

Take http://10.94.120.124:8000/ A/B?c=1&d=4 as an example:

  • After the http request comes, the port number monitored in the server global block is matched to the corresponding server. Then proceed to the matching of the location path.

  • First match location /. In this matching rule, first search for the $uri file in the root directory (/home/leimengyao/api/app/htdocs) through try_files; if there is no match, then look for the root directory $uri/ directory; if there is no match, the last item /index.php?$args will be matched, that is, an "internal sub-request" is issued, which is equivalent to nginx initiating an http request to http://10.94.120.124 :8000/ index.php?c=1&d=4

  • This sub-request will be caught location ~ \.php${ ... }, that is, enter the FastCGI processing program (nginx needs to be configured through the FastCGI module, and the relevant php parameters are passed to php-fpm for processing. The fastcgi_pass related parameters are set in this item, and the resources requested by the user are sent Parse php-fpm. The related configuration syntax of nginx FastCGI module will be introduced below). The specific URI and parameters are passed to FastCGI and WordPress programs in REQUEST_URI, so they are not affected by URI changes! ! ! ! .

     
    1. public static function detectPath() {

    2. if (!empty($_SERVER['SCRIPT_URL'])) {

    3. $path = $_SERVER['SCRIPT_URL'];

    4. } else {

    5. //as: www.baidu.com/A/B?saadf=esdf

    6. if (isset($_SERVER['REQUEST_URI'])) {

    7. //$_SERVER['REQUEST_URI']="/m/test?saadf=esdf";

    8. $request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    9. if (false !== $request_uri) {

    10. $path = $request_uri;

    11. //echo $path; /A/B

    12. //exit;

    13. } elseif ($_SERVER['REQUEST_URI'] && strpos($_SERVER['REQUEST_URI'], '?') !== false) {

    14. $path = strstr($_SERVER['REQUEST_URI'], '?', true);

    15. }

    16. } else {

    17. $path = $_SERVER['PHP_SELF'];

    18. }

    19. }

    20. return $path;

    21. }

3. Nginx configuration. PHP FastCGI

You need to understand some documents first. (Nginx.conf + fastcgi_params + php-fpm.conf + php.ini)

  • The fastcgi_params file is generally stored under /usr/local/etc/nginx (Ubuntu can be stored under /etc/nginx), which defines basic environment variables for the FastCGI module. These fastcgi environment variables will be used when configuring the fastcgi_params of nginx. The content is as follows:

  • The PHP FastCGI module of Nginx.conf allows nginx to work with FastCGI and controls which parameters will be passed safely. The meaning of common fastcgi parameter configuration will be introduced in detail below. The configuration example is as follows:

     
    1. location / {

    2. fastcgi_pass   localhost:9000;

    3. fastcgi_index  index.php;

    4.  

    5. fastcgi_param  SCRIPT_FILENAME  /home/www/scripts/php$fastcgi_script_name;

    6. fastcgi_param  QUERY_STRING     $query_string;

    7. fastcgi_param  REQUEST_METHOD   $request_method;

    8. fastcgi_param  CONTENT_TYPE     $content_type;

    9. fastcgi_param  CONTENT_LENGTH   $content_length;

    10. }

 

https://www.jianshu.com/p/9bae5c49a163

       Checking found that the configuration file directory is in the /etc directory, but loading php.ini is displayed as none; switch to the directory under /etc to check that there is indeed no php.ini file.

Copy php.ini.default to php.ini, execute php --ini again to check that the php.ini file is loaded successfully

The php -m view will list the installed extensions of the command line PHP Cli.

View the php extension installation directory command: php-config | grep -i extension ( http://www.blogdaren.com/post-2520.html )

Switch to this directory to view the expansion

Secondly, understand the meaning of some common fastcgi configurations in nginx.conf

  • fastcgi_pass: This parameter sets the communication mode between nginx and php-fpm. There are two communication modes between nginx and php-fpm, one is in socket format and the other is in tcp format. You can configure both ways, but you must ensure that the monitoring mode configured by nginx is consistent with the monitoring mode configured by php-fpm.conf! ( https://segmentfault.com/q/1010000004854045 , https://www.jianshu.com/p/eab11cd1bb28 )

Among them, TCP is IP and port, which can cross servers. And UNIX Domain Socket does not go through the network and can only be used in scenarios where Nginx and PHP-FPM are on the same server. Which one you use depends on your PHP-FPM configuration:
Method 1:
php-fpm.conf: listen = 127.0.0.1:9000
nginx.conf: fastcgi_pass 127.0.0.1:9000;
Method 2:
php-fpm.conf: listen = /tmp/php-fpm.sock
nginx.conf: fastcgi_pass unix: /tmp/php-fpm.sock;
where php-fpm.sock is a file, generated by php-fpm, and the type is srw-rw----.

 

UNIX Domain Socket can be used for two processes that are not related. It is a widely used IPC mechanism. For example, the communication between X Window server and GUI program is through UNIX Domain Socket. This communication method occurs in the system kernel instead of Will spread across the network. Both UNIX Domain Socket and long connections can avoid the frequent creation of short TCP connections that cause too many TIME_WAIT connections. For the two programs of inter-process communication, the process of UNIX Domain Socket will not go to the TCP layer. , Directly in the form of a file, communicate with a stream socket. If it is a TCP Socket, you need to go to the IP layer. For a server that is not the same, the TCP Socket goes more.

UNIX Domain Socket:
Nginx <=> socket <=> PHP-FPM
TCP Socket (local loopback):
Nginx <=> socket <=> TCP/IP <=> socket <=> PHP-FPM
TCP Socket (Nginx and PHP- FPM is located on a different server):
Nginx <=> socket <=> TCP/IP <=> physical layer <=> router <=> physical layer <=> TCP/IP <=> socket <=> PHP-FPM

  • fastcgi_index:

  • fastcgi_param:

 

After all the above configuration files are modified, you need to restart nginx and php-fpm for the modified content to take effect:

Three. Nginx realizes PHP dynamic analysis. Common errors in the configuration process

  1. php-fpm needs some configuration changes (timeout duration: request_slowlog_timeout and other    php-fpm request_terminate_timeout set improperly caused by 502 errors )

  2. Nginx-configuration error (fastcgi_param SCRIPT_FILENAME)

  3. Nginx + Php-fpm a magical 502 error

  4. nginx+php-fpm opens index.php and shows blank

  5. php international plug-in installation, debug plug-in installation (extension php.ini)

  6. php cache information is turned off ( https://www.cnblogs.com/JohnABC/p/3529786.html    !! Turning on the cache will cause many problems, depending on the situation)

  7. ? PHP execution process: https://www.jianshu.com/p/042c56e08939

Four. Configure the artifact PhpStrom development environment under Mac

https://blog.csdn.net/tfy_2425482491/article/details/79377672

Click debug to report the following error: install debug extension

Five. php dependency management tool-composer

 

Six. Other

    redis(https://www.jianshu.com/p/018bbf5ff42a

    php    call_user_func_array(https://www.jianshu.com/p/1c0f30d8722d

 

references:

http://www.cnblogs.com/mangguoxiansheng/p/5967745.htmll

https://segmentfault.com/q/1010000004854045

nginx rewrite rules  https://segmentfault.com/a/1190000002797606

 

Guess you like

Origin blog.csdn.net/benli8541/article/details/113091543