search
HomeOperation and MaintenanceNginxHow to configure and optimize FastCGI in Nginx

fastcgi:

fastcgi is developed and improved from cgi. The main disadvantage of the traditional cgi interface method is poor performance, because every time the http server encounters a dynamic program, the script parser needs to be restarted to perform parsing, and then the results are returned to the http server. This is almost unavailable when dealing with high concurrent access. In addition, the traditional cgi interface method has poor security and is rarely used now.

The fastcgi interface mode adopts the c/s structure, which can separate the http server and the script parsing server, and start one or more script parsing daemons on the script parsing server. Every time the http server encounters a dynamic program, it can be delivered directly to the fastcgi process for execution, and then the result is returned to the browser. This method allows the http server to exclusively process static requests or return the results of the dynamic script server to the client, which greatly improves the performance of the entire application system.

nginx does not support direct calling or parsing of external programs. All external programs (including PHP) must be called through the fastcgi interface. The fastcgi interface is a socket under Linux (this socket can be a file socket or an ip socket). In order to call a cgi program, a fastcgi wrapper is also needed (a wrapper can be understood as a program used to start another program). This wrapper is bound to a fixed socket, such as a port or file socket. When nginx sends a cgi request to this socket, through the fastcgi interface, the wrapper receives the request and then spawns a new thread. This thread calls the interpreter or external program to process the script and read the return data; then, the wrapper The returned data is passed to nginx along the fixed socket through the fastcgi interface; finally, nginx sends the returned data to the client. This is the entire operation process of nginx fastcgi. The detailed process is as shown in the figure.

How to configure and optimize FastCGI in Nginx

Example:

How to configure and optimize FastCGI in Nginx

Optimization configuration example of fastcgi parameters in nginx

After configuring nginx fastcgi, in order to ensure the high-speed and stable operation of the php environment under nginx, some fastcgi optimization instructions need to be added. An optimization example is given below. Add the following code to the http level in the nginx main configuration file.

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=test:10m inactive=5m; 
fastcgi_connect_timeout 300; 
fastcgi_send_timeout 300; 
fastcgi_read_timeout 300; 
fastcgi_buffer_size 64k; 
fastcgi_buffers 4 64k; 
fastcgi_busy_buffers_size 128k; 
fastcgi_temp_file_write_size 128k; 
fastcgi_cache test; 
fastcgi_cache_valid 200 302 1h; 
fastcgi_cache_valid 301 1d; 
fastcgi_cache_valid any 1m;

The meaning of the above code:

  • In the first line of code, the file path, directory structure level, keyword area storage time and non-fastcgi cache are set. Activity data deletion time.

  • fastcgi_connect_timeout specifies the timeout for connecting to the backend fastcgi.

  • fastcgi_send_timeout specifies the timeout for sending requests to fastcgi. This value is the timeout for sending requests to fastcgi after two handshakes have been completed.

  • fastcgi_read_timeout specifies the timeout for receiving fastcgi responses. This value is the timeout for receiving fastcgi responses after two handshakes have been completed.

  • fastcgi_buffer_size is used to specify the size of the buffer needed to read the first part of the fastcgi response. This value indicates that a 64kb buffer will be used to read the first part of the response (response header) , can be set to the buffer size specified by the fastcgi_buffers option.

  • fastcgi_buffers specifies how many and how large buffers need to be used locally to buffer fastcgi response requests. If the page size generated by a php script is 256kb, then four 64kb buffers will be allocated for caching; if the page size is greater than 256kb, then the part greater than 256kb will be cached in the path specified by fastcgi_temp, but this is not Good approach, since data can be processed faster in memory than on a hard drive. Generally, this value should be the middle value of the page size generated by the PHP scripts in the site. If the page size generated by most scripts in the site is 256kb, then this value can be set to "16 16k", "4 64k", etc.

  • The default value of fastcgi_busy_buffers_size is twice the size of fastcgi_buffers.

  • fastcgi_temp_file_write_size indicates how large a data block is used when writing cache files. The default value is twice that of fastcgi_buffers.

  • Enable fastcgi cache and name it refers to the role of fastcgi_cache. Turning on the cache is very useful, it can effectively reduce the load on the CPU and prevent 502 errors from occurring, but turning on the cache can also cause many problems, depending on the specific situation.

  • fastcgi_cache_valid, fastcgi is used to specify the cache time of the response code. The value in the example indicates that 200 and 302 responses will be cached for one hour, 301 responses will be cached for 1 day, and other responses will be cached for 1 minute.

The above is the detailed content of How to configure and optimize FastCGI in Nginx. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Using NGINX: Optimizing Website Performance and ReliabilityUsing NGINX: Optimizing Website Performance and ReliabilityMay 09, 2025 am 12:19 AM

NGINX can improve website performance and reliability by: 1. Process static content as a web server; 2. forward requests as a reverse proxy server; 3. allocate requests as a load balancer; 4. Reduce backend pressure as a cache server. NGINX can significantly improve website performance through configuration optimizations such as enabling Gzip compression and adjusting connection pooling.

NGINX's Purpose: Serving Web Content and MoreNGINX's Purpose: Serving Web Content and MoreMay 08, 2025 am 12:07 AM

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

NGINX Unit: Streamlining Application DeploymentNGINX Unit: Streamlining Application DeploymentMay 07, 2025 am 12:08 AM

NGINXUnit simplifies application deployment with dynamic configuration and multilingual support. 1) Dynamic configuration can be modified without restarting the server. 2) Supports multiple programming languages, such as Python, PHP, and Java. 3) Adopt asynchronous non-blocking I/O model to improve high concurrency processing performance.

NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

Deploying Applications with NGINX Unit: A GuideDeploying Applications with NGINX Unit: A GuideMay 04, 2025 am 12:03 AM

NGINXUnitischosenfordeployingapplicationsduetoitsflexibility,easeofuse,andabilitytohandledynamicapplications.1)ItsupportsmultipleprogramminglanguageslikePython,PHP,Node.js,andJava.2)Itallowsdynamicreconfigurationwithoutdowntime.3)ItusesJSONforconfigu

NGINX and Web Hosting: Serving Files and Managing TrafficNGINX and Web Hosting: Serving Files and Managing TrafficMay 03, 2025 am 12:14 AM

NGINX can be used to serve files and manage traffic. 1) Configure NGINX service static files: define the listening port and file directory. 2) Implement load balancing and traffic management: Use upstream module and cache policies to optimize performance.

NGINX vs. Apache: Comparing Web Server TechnologiesNGINX vs. Apache: Comparing Web Server TechnologiesMay 02, 2025 am 12:08 AM

NGINX is suitable for handling high concurrency and static content, while Apache is suitable for dynamic content and complex URL rewrites. 1.NGINX adopts an event-driven model, suitable for high concurrency. 2. Apache uses process or thread model, which is suitable for dynamic content. 3. NGINX configuration is simple, Apache configuration is complex but more flexible.

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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