<>

1. CGI What's this

CGI yescommon gateway interface Abbreviation, Everyone translates it as a universal Gateway Interface, But unfortunately. We can't see the meaning of fame.

We know,web The content processed by the server is static, To process dynamic content, Need to rely onweb application program, asphp,jsp,python,perl etc.. howeverweb
server How to pass dynamic requests to these applications? It depends oncgi Agreement. You're right, It's an agreement. that isweb
server andweb Specification for application communication. Let me put it another way, adoptcgi Agreement, Combined with the builtweb application program, Can letweb
server Can also" Handle" Dynamic request( Or say, When a user accesses a specific resource, Can trigger the execution of aweb Application to implement specific functions), You must know why you need to put double quotes when dealing with two words.

Simple Editioncgi Work as follows:



for example, Search for a keyword in Google search"http", CorrespondingURL by:
https:
//www.google.com/search?q=http&oq=http&aqs=chrome..69i57j69i60l4j0.1136j0j8&sourceid=chrome&ie=UTF-8
When Googleweb
server After receiving the request, First analyze this.url, From which I know to executesearch program, And I know a series of things to pass on tosearch Parameters of and their correspondingvalue.web
server These program parameters and other environment variables will becgi Agreement passedTCP Or socket to the startedcgi program( May becgi process, Or loaded modulescgi Modular). Whencgi Process receivedweb
server After request, callsearch Procedure and execution, Parameters are also passed tosearch program.search After execution,cgi process/ Thread returns processing results toweb
server,web server Back to browser.


There are many ways to do thiscgi program, But righthttp For the request method of, onlyget andpost Two methods allow executioncgi Script( Abovesearch program). Actuallypost The internal nature of the method isget Method, Just sendinghttp Request time,get andpost Method pairurl Parameters in are handled differently.

Can be written in any languageCGI, But some languages are good at it, Some languages are very cumbersome, For examplebash
shell Development, So we need to useecho Wait for the print statement to put the execution result in a huge number of incomparablehtml Output to client in tag of. Often used for writingCGI Language hasperl,php,python etc.java Can also write, butjava Ofservlet Fully achievableCGI Function, And more optimization, Better for development.

<>

2. Explanation of various terms


Tell the truth, For someone who hasn't been exposed to a programming language, Rigid contactcgi There must be a lot of questions about the concept, What the hell is this, Things that deal with dynamic content are not likephp The same application, Followcgi How much is it,fastcgi What is it again?? I think, Obsessive-compulsive disorder patients of non academic background( Including me) It's bound to be tossed around by these concepts.

withphp take as an example, I will explain the concept of a dynamic request briefly.

* cgi: It's a protocol. adoptcgi Agreement,web server Dynamic requests and related parameters can be sent to applications that specifically handle dynamic content.
* fastcgi: It's also a protocol, nothing butcgi Optimized version.cgi Poor performance,fastcgi On the basis of it, the improvement is made.
* php-cgi:fastcgi It's a protocol, andphp-cgi This protocol is implemented. But this kind of implementation is bad. It's single process, A process processes a request, Process destroyed after processing.
* php-fmp: Yes.php-cgi Improved version, It directly manages multiplephp-cgi process/ thread. In other words,php-fpm yesphp-cgi Process manager for
So it's kind offastcgi Implementation of the protocol. To some extent,php-fpm Andphp Relationship, andtomcat Yesjava The relationship is similar.
* cgi process/ thread: stayphp upper, Namelyphp-cgi process/ thread. Dedicated to receivingweb server Dynamic request for, Call and initializezend virtual machine.
* cgi Script: Executedphp Source code file.
* zend virtual machine: Yesphp Lexical analysis of documents, Syntax analysis, Compile intoopcode, And execute. Final closurezend virtual machine.
* cgi process/ Thread andzend Virtual machine relationship:cgi Process call and initializezend Various environments of virtual machine.
withphp-fpm take as an example,web server The process from forwarding the dynamic request to the end is roughly as follows:



And eachphp-cgi The role of the process includes:( Some functions are classified incorrectly, Please ignore. It's enough to know the general function)



Be careful, althoughphp-fpm The full name isPHP FastCGI Process Manager, But strictly speaking,php-fpm Nofastcgi Process manager for, Butphp
fastcgi Namelyphp-cgi Process manager for.fastcgi It's just an agreement, Not process. Just likehttp Same protocol,apache Its implementation ishttpd,nginx The realization of it is callednginx.


Explain again,cgi andfastcgi It's a protocol. Various support andWEB Interactive programming language paircgi/fastcgi Each protocol has its own implementation( Of course, Can write in any languagecgi Script), andphp Upperphp-cgi andphp-fpm Exactlyphp Yesfastcgi Implementation of the protocol.

<>

3. web server andCGI Interaction mode of

web server Yescgi process/ Thread, Its function is to initiate dynamic processing of requests, Pass some parameters and environment variables, Final receptioncgi Results returned by. In a more popular and less rigorous way,web
server adoptcgi/fastcgi Protocol forwards dynamic request to executioncgi Script application. Pass belowhttpd.conf The forwarding configuration in should be easy to understand(httpd andphp-fpm Interaction):
ProxyRequests off ProxyPassMatch ^/(.*\.php)$ fcgi://127.0.0.1:9000/usr
/local/apache/htdocs/$1
With the most typicalapache httpd andphp take as an example, abouthttpd Speaking,web server andphp-cgi Yes3 Interaction modes.

* cgi Pattern:httpd Receive a dynamic requestfork Onecgi process,cgi Process returns results tohttpd Post process self destruction.
* Dynamic module mode
: takephp-cgi Module( for examplephp5_module) Compile inhttpd. stayhttpd Module loaded on startup, The corresponding module will also be activated when loading,php-cgi And it started.( notes: Correct a small mistake, Many people think that dynamically compiled modules can be loaded and called at any time when they need to, They stop when they don't need to, Not really. Same as statically compiled modules, Dynamically loaded modules are added to the activation list when they are loaded, Whether you use it or not, It's all running onapache
httpd Internal. May refer toLoadModule Official Manual of the directive)
* php-fpm Pattern
: Usephp-fpm Administrationphp-cgi, herehttpd No more controlphp-cgi Start of process. Can bephp-fpm Independent operation in nonweb Server, To achieve the so-called dynamic and static separation.
Actually, With modulemod_fastcgi It can also be realizedfastcgi Pattern. withcgi equally, The inborn defect of management mode determines that this is not a good method.

<>

3.1 CGI Pattern


UseCGI Mode time, When a dynamic request arrives,httpd Temporarily start acgi interpreter, And passcgi Protocol forwarding what to run. Whencgi After the script runs, Return results tohttpd, Then?cgi Interpreter process self destructs. When multiple dynamic requests arrive, Multiple will be started successivelycgi interpreter. therefore, This method is extremely inefficient.


Annotatephp5_module OfLoadModule Related post, Useaction Instruction specifies to usecgi Type of operation. But pay attention to,action Instruction ismod_action Provided, So the module must already be loaded.

for example: AppointMIME Type isimage/gif Requested use ofimages.cgi Function. Obviously,images.cgi You have to write the script first.
Action image/gif /cgi-bin/images.cgi
You can also addhandler To compound file types, Reuse acgi Script to run thishandler Any type in.
AddHandler my-file-type .xyz Action my-file-type "/cgi-bin/program.cgi"
aboutphp Speaking, You can use the installationphp Timebin Provided in the directoryphp-cgi Procedure ascgi program.
[[email protected] php]# ls /usr/local/php/bin/ pear peardev pecl phar phar.phar php
php-cgi php-config phpize# Copy toapache Defaultcgi-bin Directory, Convenient management [[email protected] php]# cp
/usr/local/php/bin/php-cgi /usr/local/apache/cgi-bin/ # stayhttpd.conf Add the following lines to
Action application/x-httpd-php /usr/local/php/bin/cgi-bin/php-cgi
<>

3.2 Module mode


Compilephp Time, takephp5_module Module compiled toapache in, For example, when compilingphp When in./configure Add in configuration"--with-apxs2=/usr/local/apache/bin/apxs".


In this interactive mode,httpd Load and activate at startupphp_module. In other words,php-cgi Resident inhttpd Internal process. When a dynamic request arrives,httpd No more generationcgi interpreter, Instead, it forwards the dynamic request directly to its internalphp-cgi.

Configuration utility this interaction mode is very simple, Just useLoadModule Loadphp_module, Add the correspondingMIME The processor can.
LoadModule php5_module modules/libphp5.so # staymime Add corresponding type in module <IfModule
mime_module> AddType application/x-httpd-php .php AddType
applicaiton/x-httpd-php-source .phps</IfModule>
<>

3.3 php-fpm mode


I said before.php-fpm yesphp-cgi Process manager for. This kind of interaction actually makesphp-cgi Independent ofhttpd The way, Current basic usephp-fpm How to managephp-cgi process. In other words, In this mode,php-cgi andhttpd It's separated, Their separation means that the dynamic and static separation of the request becomes possible:httpd andphp-fpm Running on different servers. After dynamic and static separation, The pressure is also spread to the respective servers.

Must letphp-fpm Run in this way, Need to be compiled in./configure Add in configuration options"--enable-fpm" option. Of course, We have to start.php-fpm service. for example:
service php-fpm start

suchphp-cgi The process opens the port( default9000) wait forhttpd Forward dynamic requests. Must lethttpd Ability to forward requests tophp-cgi upper, Need tohttpd.conf Close forward agent in, And set upfastcgi Protocol proxy parameters. for example, Forwarding to192.168.100.54 Host computerphp-fpm.
# Load agent module LoadModule proxy_module modules/mod_proxy.so LoadModule
proxy_fcgi_module modules/mod_proxy_fcgi.so# Add toMIME type AddType
application/x-httpd-php .phpAddType application/x-httpd-php-source .phps #
Configure the forwarding agent in the virtual host to be forwarded ProxyRequests off ProxyPassMatch ^/(.*\.php)$ fcgi:/
/192.168.100.54:9000/usr/local/apache/htdocs/$1