Home >Backend Development >PHP Tutorial >How to quickly and correctly configure a complete php environment (nginx and php)

How to quickly and correctly configure a complete php environment (nginx and php)

慕斯
慕斯forward
2021-05-20 15:12:1210602browse

How to quickly and correctly configure a complete php environment (nginx and php)

How to quickly and correctly configure a complete php environment (nginx and php)

First, let’s understand how nginx works: https://blog.csdn. net/hguisu/article/details/8930668

1.nginx implements PHP dynamic parsing principle

nginx is a high-performance http server and reverse proxy server. That is to say, nginx can be used as an HTTP server for website publishing and processing, and it can also be used 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 parsing server, and finally the processing results will be returned to nginx . That is, nginx forwards dynamic requests to the backend php-fpm through the reverse proxy function, thereby realizing support for PHP parsing. This is the basic principle of Nginx implementing PHP dynamic parsing.

First you need to understand some concepts. (nginx php-fpm fastcgi)

  • Nginx is a non-blocking IO & IO multiplexing model. Through the epoll-like function provided by the operating system, you can Handle multiple client requests in one thread. The process of Nginx is a thread, that is, there is only one thread in each process, but this thread can serve multiple clients.
  • PHP-FPM is a blocking single-thread model, pm.max_children specifies the maximum number of processes, pm.max_requests specifies how many processes each process handles Restart after a request (because PHP occasionally has memory leaks, it needs to be restarted). Each process of PHP-FPM also has only one thread, but one process can only serve one client at the same time.
  • fastCGI: In order to solve the communication problem between different language interpreters (such as php, python interpreters) and webserver, the cgi protocol appeared. As long as you write a program according to the cgi protocol, you can achieve communication between the language interpreter and 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 is completed. If there are 10,000 requests, the php-cgi process needs to be forked and killed 10,000 times. fastcgi is an improved version of cgi. After fast-cgi processes a request each time, it will not kill the process, but retain the process so that the process can handle multiple requests at one time. Greatly improved efficiency.

Supplement: Relevant knowledge about reverse proxy and forward proxy (in short, forward proxy-acts for the client; reverse proxy-acts for the server)

The purpose of the positive agent:
(1) Access the resources that could not be accessed, such as Google
(2) You can do cache, accelerate the access resources
(3) Access to client access authorization, Go online for authentication
             (4) The proxy can record user access records, online behavior management, and hide user information from the outside)

Use of reverse proxy: Reverse proxy, "it acts as a proxy for the server", mainly When used in distributed deployment of server clusters, the reverse proxy hides server information.
(1) To ensure the security of the internal network, the reverse proxy is usually used as the address of the public network. The web server is the inner network
(2) load balancing.

2.nginx implements PHP dynamic parsing. How to configure nginx

1. Understand the common sense related to nginx configuration (nginx.conf )

nginx.conf composition and basic configuration syntax are explained in another article. Here we will give a brief introduction to several syntaxes used to parse PHP configuration:

    try_files $uri $uri/ /index.php$is_args$args : (https://blog.51cto.com/13930997/2311716,,, a pitfall in Nginx try_files --- the last one of
  • try_files The location (fall back) is special, it will issue an internal "sub-request" instead of directly searching for the file in the file system!!!)
  • Configuring nginx location ~ \.php$ A question (https://segmentfault.com/q/1010000012298020)
  • rewrite (https://segmentfault.com/a/1190000002797606)
  • Appendix: nginx configuration related syntax (note nginx also contains some available global variables, see the link for details; you can also view the official nginx documentation http://www.nginx.org/ https://www.cnblogs.com/knowledgesea/p/5175711.html )

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 arrives, the process is as follows:

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

  • After the http request arrives, the corresponding server is matched through the port number listened in the server global block. Then proceed to match the location path.
  • First match location /. In this matching rule, first search for $uri files in the root directory (/home/leimengyao/api/app/htdocs) through try_files; If there is no match, then check whether there is a $uri/ directory in the root directory; if there is no match, then match the last item /index.php?$args, that is, issue a "Internal sub-request" 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 location ~ \.php${ ... }catch, that is, enter the FastCGI processing program (nginx needs to be configured through the FastCGI module and pass the relevant php parameters to php-fpm for processing. Fastcgi_pass is set in this item Relevant parameters, send the resources requested by the user to php-fpm for parsing, which involves the relevant 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! ! ! ! .
    public static function detectPath() {
        if (!empty($_SERVER['SCRIPT_URL'])) {
            $path = $_SERVER['SCRIPT_URL'];
        } else {
            //as: www.baidu.com/A/B?saadf=esdf
            if (isset($_SERVER['REQUEST_URI'])) {
              //$_SERVER['REQUEST_URI']="/m/test?saadf=esdf";
                $request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
                if (false !== $request_uri) {
                    $path = $request_uri;
                  //echo $path; /A/B
                  //exit;
            } elseif ($_SERVER['REQUEST_URI'] && strpos($_SERVER['REQUEST_URI'], '?') !== false) {
                $path = strstr($_SERVER['REQUEST_URI'], '?', true);
            }
            } else {
                $path = $_SERVER['PHP_SELF'];
            }
        }
        return $path;
    }

3. Nginx configuration. PHP FastCGI

First you need to understand some files. (nginx.conf fastcgi_params php-fpm.conf php.ini)

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

  • Nginx.conf The PHP FastCGI module of allows nginx to work together with FastCGI and controls which parameters will be passed safely. The meaning of common fastcgi parameter configurations will be introduced in detail below. The configuration example is as follows:
    location / {
      fastcgi_pass   localhost:9000;
      fastcgi_index  index.php;
     
      fastcgi_param  SCRIPT_FILENAME  /home/www/scripts/php$fastcgi_script_name;
      fastcgi_param  QUERY_STRING     $query_string;
      fastcgi_param  REQUEST_METHOD   $request_method;
      fastcgi_param  CONTENT_TYPE     $content_type;
      fastcgi_param  CONTENT_LENGTH   $content_length;
    }

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

  • php-fpm .conf
  • php.ini Use php --ini to view the configuration file path loaded by php(https://www.jianshu.com/p /a118f10d738c)

I checked and found that the configuration file directory is in the /etc directory, but loading php.ini shows none; switch to the directory under /etc and check, it is indeed not there php.ini file.

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

php -m View will list the extensions installed by 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 extension

Secondly, learn about some common fastcgi configurations in nginx.conf Meaning

  • fastcgi_pass:该参数设置的是nginx与php-fpm的通信方式,nginx和php-fpm的通信方式有两种,一种是socket形式,一种是tcp形式。配置两种方式都可以,但是必须保证nginx配置的监听方式,和php-fpm.conf配置的监听方式保持一致性!(https://segmentfault.com/q/1010000004854045、https://www.jianshu.com/p/eab11cd1bb28)

其中TCP是IP加端口,可以跨服务器.而UNIX Domain Socket不经过网络,只能用于Nginx跟PHP-FPM都在同一服务器的场景.用哪种取决于你的PHP-FPM配置:
方式1:
php-fpm.conf: listen = 127.0.0.1:9000
nginx.conf: fastcgi_pass 127.0.0.1:9000;
方式2:
php-fpm.conf: listen = /tmp/php-fpm.sock
nginx.conf: fastcgi_pass unix:/tmp/php-

<br/>

fpm.sock;
其中php-fpm.sock是一个文件,由php-fpm生成,类型是srw-rw----.

 

UNIX Domain Socket可用于两个没有亲缘关系的进程,是目前广泛使用的IPC机制,比如X Window服务器和GUI程序之间就是通过UNIX Domain Socket通讯的.这种通信方式是发生在系统内核里而不会在网络里传播.UNIX Domain Socket和长连接都能避免频繁创建TCP短连接而导致TIME_WAIT连接过多的问题.对于进程间通讯的两个程序,UNIX Domain Socket的流程不会走到TCP那层,直接以文件形式,以stream socket通讯.如果是TCP Socket,则需要走到IP层,对于非同一台服务器上,TCP Socket走的就更多了.

UNIX Domain Socket:
Nginx 96b4fef55684b9312718d5de63fb7121 socket 96b4fef55684b9312718d5de63fb7121 PHP-FPM
TCP Socket(本地回环):
Nginx 96b4fef55684b9312718d5de63fb7121 socket 96b4fef55684b9312718d5de63fb7121 TCP/IP 96b4fef55684b9312718d5de63fb7121 socket 96b4fef55684b9312718d5de63fb7121 PHP-FPM
TCP Socket(Nginx和PHP-FPM位于不同服务器):
Nginx 96b4fef55684b9312718d5de63fb7121 socket 96b4fef55684b9312718d5de63fb7121 TCP/IP 96b4fef55684b9312718d5de63fb7121 物理层 96b4fef55684b9312718d5de63fb7121 路由器 96b4fef55684b9312718d5de63fb7121 物理层 96b4fef55684b9312718d5de63fb7121 TCP/IP 96b4fef55684b9312718d5de63fb7121 socket 96b4fef55684b9312718d5de63fb7121 PHP-FPM

  • fastcgi_index:
  • fastcgi_param:

 

以上配置文件全部修改完成以后,需要进行重启nginx和php-fpm,修改的内容才能生效:

  • 修改配置(nginx.conf,php-fpm.conf,php.ini)需要进行的操作(修改配置的时候通过 find / -name php-fpm.conf命令来查找),另外重启php-fpm(mac重启php-fpm)和nginx (nginx -s reload     https://www.jianshu.com/p/2726ca520f4a 、  https://www.jianshu.com/p/9bae5c49a163)

三.nginx实现php动态解析.之配置过程中常见错误

  1. php-fpm需要进行一些配置修改(超时时长:request_slowlog_timeout等   php-fpm 的request_terminate_timeout设置不当导致的502错误)
  2. Nginx-配置误区 (fastcgi_param SCRIPT_FILENAME)
  3. Nginx + Php-fpm 一个神奇的502错误
  4. nginx+php-fpm打开index.php显示空白
  5. php国际化插件安装、debug插件安装(extension  php.ini)
  6. php缓存信息关闭(https://www.cnblogs.com/JohnABC/p/3529786.html   !!开启缓存会引起许多问题,视情况而定
  7. ?php执行流程https://www.jianshu.com/p/042c56e08939

四.Mac下配置神器PhpStrom开发环境

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

点击debug报如下错误:安装debug扩展

五.php依赖管理工具-composer

 

六.其他

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

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

推荐学习:《PHP视频教程 

The above is the detailed content of How to quickly and correctly configure a complete php environment (nginx and php). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete