search
HomeBackend DevelopmentPHP TutorialIntroduction to the principle of nginx and php executing requests

This article brings you an introduction to the principles of nginx and php execution requests. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, let’s understand the relationship between cgi, php-cgi, fastcgi and php-fpm that we often hear, and help us understand the working principle of php

cgi protocol

The cgi protocol is used to determine the webserver (such as nginx), that is, what data is passed by the content distribution server and what format the data is in.

php-cgi process interpreter

php-cgi is the cgi protocol process interpreter of php. Every time it is started, it needs to load the php.ini file -> initialize the execution environment -> process the request -> return content to the webserver -> ;php-cgi process exit process

fastcgi protocol

The fastcgi protocol is a supplement to the efficiency improvement of the cgi protocol, mainly for each request. It is necessary to start the optimization of a cgi interpreter process. It is no longer necessary for the cgi interpreter process to reload the php.ini file and initialize the execution environment every time it receives a webserver request.

php-fpm Process Manager

php-fpm is the implementation of the fastcgi protocol and is a process manager. It includes master and worker processes at startup. The master process listens on the port and receives requests from the webserver. There are generally multiple worker processes, each worker Each process has a cgi process interpreter, which is used to execute PHP code

php startup and working principle

When starting phpfpm, the master process will be started, the php.ini file will be loaded, and the execution environment will be initialized. And start multiple worker processes. Each time a request comes, the request will be passed to the worker process for processing

php smooth restart principle

Every time after modifying the php.ini configuration and restarting, a new worker process will be started to load the new Configuration, and the previously existing process will be destroyed after the work is completed, so a smooth restart is achieved

nginx working principle

If you want to understand the principle of cooperation between nginx and php, you need to understand it first The server part in the nginx configuration file

server {
    listen       80; #监听80端口,接收http请求
    server_name  www.example.com; #一般存放网址,表示配置的哪个项目
    root /home/wwwroot/zensmall/public/; # 存放代码的根目录地址或代码启动入口
    index index.php index.html; #网站默认首页
    
    #当请求网站的url进行location的前缀匹配且最长匹配字符串是该配置项时,按顺序检查文件是否存在,并返回第一个找到的文件
    location / {
          #try_files,按顺序检查文件是否存在,返回第一个找到的文件
          #$uri代表不带请求参数的当前地址
          #$query_string代表请求携带的参数
          try_files   $uri $uri/ /index.php?$query_string; #按顺序检查$uri文件,$uri地址是否存在,如果存在,返回第一个找到的文件;如果都不存在,发起访问/index.php?$query_string的内部请求,该请求会重新匹配到下面的location请求
    }
    
     #当请求网站的php文件的时候,反向代理到php-fpm去处理
    location ~ \.php$ {
          include       fastcgi_params; #引入fastcgi的配置文件
          fastcgi_pass   127.0.0.1:9000; #设置php fastcgi进程监听的IP地址和端口
          fastcgi_index  index.php; #设置首页文件
          fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name; #设置脚本文件请求的路径
    }
}

The overall meaning of the above server configuration is: every time nginx listens to a URL request on port 80, it will perform location matching on the URL. If the / rule is matched, the internal request will be redirected and the internal request of /index.php?$query_string will be initiated, and the corresponding location configuration rule will send the request to the master process of php-fpm listening on port 9000

Summary

The following summarizes the simplest user request process:

User accesses the domain name->Domain name performs DNS resolution->Requests to the corresponding IP server and port->nginx Listen to the request of the corresponding port->nginx performs location matching on the URL->Execute the rules under the matching location->nginx forwards the request to php->php-fpm’s master process monitors the nginx request->master process Assign the request to one of the idle worker processes ->The worker process executes the request->The worker process returns the execution result to nginx->nginx returns the result to the user

The above is the detailed content of Introduction to the principle of nginx and php executing requests. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools