search
HomeBackend DevelopmentPHP TutorialDetailed description of nginx basic configuration

1. Advantages and disadvantages of Apache server and nginx:
We have used Apache extensively as HTTPServer before.
Apache has excellent performance and can provide a variety of rich functions through modules.
1) First of all, Apache's response to the client supports concurrency. After running the httpd daemon process, it will generate multiple child processes/threads at the same time, and each child process/thread responds to the client's request respectively;
2) In addition, Apache can provide static and dynamic services. For example, the parsing of PHP is not implemented through CGI with poor performance but through a module that supports PHP (usually mod_php5, or apxs2).
3) Disadvantages:
Therefore, this type of Server, usually called Apache, is a process-based server, which is a multi-process HTTP Server, because it needs to create a child process/thread to respond to each user request;
The disadvantage of this is that if there are many concurrent requests (which is very common in large portals), a lot of threads will be needed, which will occupy a lot of system resources, CPU and memory. Therefore, concurrent processing is not Apache's strength.
4)Solution:
Currently, there is another WebServer that performs better in terms of concurrency, called asynchronous servers. The most famous ones are Nginx and Lighttpd. So-called asynchronous servers are event-driven in the event-driven programming model, except that concurrent requests from users usually only require a single or several threads. Therefore, it takes up very little system resources. These types are also called lightweight web servers.
For example, for 10,000 concurrent connection requests, nginx may only use a few MB of memory; while Apache may need to use hundreds of MB of memory resources.
2. Single use in practice:
1) We don’t need to introduce more about using Apache as HTTP Server alone, it is a very common application;
We introduced above that Apache's support for server-side scripts such as PHP is implemented through its own modules, and its performance is superior.
2) We can also use nginx or lighttpd alone as HTTPServer.
Similar to Apache, nginx and lighttpd can enrich the server's functions through various modules. They also configure various options through conf configuration files.
For PHP, etc., neither nginx nor lighttpd has built-in modules to support PHP, but support it through FastCGI.
Lighttpd can provide CGI, FastCGI and SCGI services through modules. Lighttpd is capable of automatically spawning FastCGI backends as well as using externally spawned processes.
nginx does not provide the function of processing PHP itself, and needs to provide FastCGI integration of PHP through third-party modules.

------------------------------- rewrites all non-http://bbs.it-home.org/ visits=> ; http://bbs.it-home.org/
server_name web90.***.com;

if ($host = "web90.***.com") {
                          rewrite ^(.*)$ http://bbs.it-home.org/$1 permanent;
        }

----------------------------------nginx stop/smooth restart#p#Paging title#e#

nginx signal control

TERM,INT close quickly
QUIT Close calmly
HUP Smooth restart, reload configuration file
USR1 reopens the log file, which is more useful when cutting logs
USR2 Smoothly upgrade executable program
WINCH gracefully closes the work process


1) Stop calmly:

kill -QUIT Nginx main process ID

kill -QUIT '/usr/local/webserver/nginx/logs/nginx.pid'


2) Quick stop:

kill -TERM Nginx main process ID

kill -TERM '/usr/local/webserver/nginx/logs/nginx.pid'

kill -INTN ginx main process number

kill -INT '/usr/local/webserver/nginx/logs/nginx.pid'

3) Force stop all nginx processes

pkill -9 nginx


1) Smooth restart

kill -HUP nginx main process ID

kill -HUP '/usr/local/webserver/nginx/logs/nginx.pid'

--------------------------nginx.conf
#p#Paging title#e#


worker_processes 8;

Specify the number of job spawn processes

Generally equal to the total number of cores of the CPU or twice the total number of cores. For example, for two quad-core CPUs, the total number of cores is 8
  1. events
  2. {
  3. use epoll; //The network i/o used Model, Linux system recommends epoll, FreeBSD recommends kqueue
  4. worker_connections 65535; //Number of allowed links
  5. }


  6. location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ { access_log off; close the log expires 30d; // Output the Header header through the expires command to implement local caching, 30 days} location ~ .*.(js|css)$ { access_log off; close the log expires 1h; } ===== ================Every

  7. {

  8. access_log off;Turn off the log

  9. expires 30d;//Output the Header header through the expires directive to implement local caching for 30 days

  10. }

  11. location ~ .*.(js|css)$

  12. {

  13. access_log off;Turn off log

  14. expires 1h;

  15. }
Copy code


===================== Cut nginx log script regularly every day

  1. vim /usr/local/webserver/nginx/sbin/cut_nginx_log.sh
  2. #!/bin/bash
  3. # This script run at 00:00

  4. # The Nginx logs path
  5. logs_path ="/usr/local/webserver/nginx/logs/";

  6. mkdir -p ${logs_path}$(date -d "yesterday" + "%Y")/$(date -d "yesterday" + "%m")/#p#Paging title#e#
  7. mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" + "%Y")/$(date -d "yesterday" + "%m")/access_$(date -d "yesterday" + "%Y%m%d").log
  8. kill -USR1 'cat /usr/local/webserver/nginx/nginx.pid'



  9. chown -R www:www cut_nginx_log.sh
  10. chmod +x cut_nginx_log.sh


  11. crontab -e
  12. 00 * * * /bin/bash /usr/local/webserver/nginx /sbin/cut_nginx_log.sh


  13. #/sbin/service crond restart
Copy code
------------nginx configuration gzip compression

Under normal circumstances, the size of compressed html, css, js, php, jhtml and other files can be reduced to 25% of the original size. In other words, the original 100k html will only have 25k left after compression. This will undoubtedly save a lot of bandwidth and also reduce the load on the server.
Configuring gzip in nginx is relatively simple

Under normal circumstances, just add the following lines of configuration to the http section of nginx.conf

Quote
gzip on;
gzip_min_length 1000;
gzip_buffers 4 8k;
gzip_types text/plain application/x-javascript text/css text/html application/xml;

Restart nginx
You can use the web page gzip detection tool to detect whether gzip is enabled on the web page
http://gzip.zzbaike.com/

---------------How to redirect nginx error page

error_page 404 /404.html;

This 404.html is guaranteed to be in the html directory under the nginx home directory. If you need to jump directly to another address after a 404 error occurs, you can directly set it as follows:


error_page 404 http://bbs.it-home.org/ ;


Common 403, 500 and other errors can be defined in the same way. #p#Paging title#e#


Special attention should be paid to the fact that the page size of the 404.html file must exceed 512k, otherwise it will be replaced by the IE browser's default error page.

----------------------------------Virtual host configuration
  1. server {
  2. Listen 80;
  3. server_name localhost;
  4. access_log /var/log/nginx/localhost.access.log;

  5. location / {
  6. root /var/www/nginx-default;
  7. index index.php index.html index.htm;
  8. }

  9. location /doc {
  10. root /usr/share;
  11. autoindex on;
  12. allow 127.0.0.1;
  13. deny all;
  14. }

  15. location /images {
  16. ” root ” /usr /share;
  17.            autoindex on;
  18.                                                        use ’s ’ using ’s ’s ’ s ’ s ’ s ‐ ‐ ‐ ‐ fastcgi_param ​ SCRIPT_FILENAME ​ /var/www/nginx-default$fastcgi_script_name;
  19.                                                                                                                                                                  incremental f.localhost.com;
  20. access_log /var/log/nginx/localhost. access.log;

  21. location / {
  22. root /var/www/nginx-default/console;
  23. index index.php index.html index.htm; } location /doc { root /usr/share; autoindex on; allow 127.0.0.1; deny all; } location /images { root /usr/share; autoindex on; } location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.p
  24. #p#page title# e#

  25. }

  26. location /doc {
  27. root /usr/share;
  28. autoindex on;
  29. allow 127.0.0.1;
  30.                                                                                                                                                         deny all;
  31.                             /usr/share;                autoindex on;
    fastcgi_index index.php;

  32. fastcgi_param SCRIPT_FILENAME /var/www/nginx -default$fastcgi_script_name;

  33.                                                                                            ‐‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ include /etc/nginx/fastcgi_params;                                                                                              .-----------------------Monitoring

    location ~ ^/NginxStatus/ {

    stub_status on; #Nginx status monitoring configuration
    }



    In this way, you can monitor the running information of Nginx through http://localhost/NginxStatus/ (the last / cannot be deleted):


    Active connections: 1
    server accepts handled requests
    1 5
    Reading: 0 Writing: 1 Waiting: 0



    The content displayed by NginxStatus means as follows: #p#Paging title#e#

    Active connections – The number of active connections currently being processed by Nginx.
    Server accepts handled requests -- A total of 14553819 connections were processed, 14553819 handshakes were successfully created (proof that there were no failures in the middle), and a total of 19239266 requests were processed (an average of 1.3 data requests were processed per handshake).
    Reading -- The number of Header information nginx reads from the client.
    Writing -- The number of Header information nginx returns to the client.
    Waiting -- When keep-alive is turned on, this value is equal to active - (reading + writing), which means that Nginx has finished processing the resident connection that is waiting for the next request command.


    ----------------------------------Static file processing

    Through regular expressions, we can let Nginx identify various static files


    location ~ .(htm|html|gif|jpg|jpeg|png|bmp|ico|css|js|txt)$ {

              root /var/www/nginx-default/html;
    access_log off;
    expires 24h;
            }

    For images, static HTML files, js script files and css style files, etc., we hope that Nginx will directly process and return them to the browser, which can greatly speed up web browsing. Therefore, for this type of file, we need to use the root directive to specify the storage path of the file. At the same time, because this type of file is not frequently modified, the expires directive is used to control its cache in the browser to reduce unnecessary requests. The expires directive can control the "Expires" and "Cache-Control" headers in the HTTP response (which controls page caching). You can write Expires using, for example, the following format:

    expires 1 January, 1970, 00:00:01 GMT;
    expires 60s;
    expires 30m;
    expires 24h;
    expires 1d;
    expires max;
    expires off;

    In this way, when you enter http://192.168.200.100/1.html, it will automatically jump to var/www/nginx-default/html/1.html

    For example, all requests under the images path can be written as:

    #p#Paging title#e#

    location ~ ^/images/ {
    root /opt/webapp/images;
    }


    ------------------------Dynamic page request processing [Cluster]

    Nginx itself does not support the popular dynamic pages such as JSP, ASP, PHP, PERL, etc., but it can send requests to back-end servers through reverse proxy, such as Tomcat, Apache, IIS, etc. to complete the request processing of dynamic pages. In the previous configuration example, we first defined some static file requests to be processed directly by Nginx, and then all other requests were sent to the backend server (Tomcat in the above example) through the proxy_pass directive. The simplest proxy_pass usage is as follows:
    location / { proxy_pass http://localhost:8080; proxy_set_header
    proxy_pass http://localhost:8080;
    proxy_set_header X-Real-IP $remote_addr;
    }





    Here we do not use a cluster, but send the request directly to the Tomcat service running on port 8080 to complete request processing like JSP and Servlet.

    When the number of page visits is very large, multiple application servers are often required to jointly undertake the execution of dynamic pages. At this time, we need to use a cluster architecture. Nginx uses the upstream directive to define a server cluster. In the complete example above, we defined a cluster named tomcats. This cluster includes three servers and a total of 6 Tomcat services. The proxy_pass instruction is written as:


    # Configuration information of all backend servers in the cluster
    Upstream tomcats {
    Server 192.168.0.11:8080 weight=10;
    Server 192.168.0.11:8081 weight=10;
    Server 192.168.0.12:8080 weight=10;
    Server 192.168.0.12:8081 weight=10;
    Server 192.168.0.13:8080 weight=10;
    Server 192.168.0.13:8081 weight=10;#p#Paging title#e#
    }
    Location / {
              proxy_pass http://tomcats;# Reverse proxy
                 include proxy.conf;
            }

    -----------------------Stress Test

    1. wget http://bbs.it-home.org//soft/linux/webbench/webbench-1.5.tar.gz
    2. tar zxvf webbench-1.5.tar.gz
    3. cd webbench-1.5
    4. make && make install

    5. #webbench -c 100 -t 10 http://192.168.200.100/info.php

    6. Parameter description: -c represents the number of concurrencies, -t represents the duration (seconds)

    7. root@ubuntu-desktop:/etc/nginx/sites-available# webbench -c 100 -t 10 http://192.168.200.100/info.php
    8. Webbench - Simple Web Benchmark 1.5
    9. Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

    10. Benchmarking: GET http://192.168.200.100/info.php
    11. clients, running 10 sec.

    12. Speed=19032 pages/min, 18074373 tes /sec.
    13. Requests: 3172 susceed, 0 failed.
    Copy code

    --------------PPC provides detailed configuration instructions for nginx


    1. #Running user
    2. user nobody;
    3. #Start process
    4. worker_processes 2;#p#Page title#e#
    5. #Global error log and PID file
    6. error_log logs/error.log notice;
    7. pid logs/nginx.pid;
    8. #Working mode and maximum number of connections
    9. events{use epoll;
    10. worker_connections 1024;}#Set the http server and use its reverse proxy function to provide load balancing support


    11. http{#Settings MIME type c include conf/mime.types;
    12. default_type application/octet -stream; E_LOCAL] '' "$ Request" $ Status $ bytes_sent ''"$http_referer" "$http_user_agent" ''"$gzip_ratio"';
    13.         log_format download'$remote_addr - $remote_user [$time_local] ''"$request" $status $bytes_sent ''"$http_referer" $http_user_agent" '"$http_range" "$sent_http_content_range"'; 4 4k;
    14.                                                                                                                                             ; P gzip_buffers 4 8K;
    15. gzip_types text/plain;
    16. output_buffers 1 32K;
    17. Postpone_output 1460;
    18. #Set Access Log
    19. Access_log Logs/Access . Log Main; m Client_header_timeout 3M ; En Client_body_timeout 3M;
    20. Send_timeout 3M;
    21. SendFile on;
    22. tcp_nopush on;
    23. tcp_nody on;
    24. keepalive_timeout 65;
    25. #Set load balancing Server list p upstream mysvr {#Weigth The parameter represents the weight. The higher the weight, the greater the chance of being assigned. " .8.2: 80 weight = 1;
    26. Server 192.168.8.3:80 weight = 6;
    27. }
    28. #Set the virtual host
    29. server {Listen 80;
      A Server_name 192.168.8.1 www.okpython.com;

    30. Charset gb2312;

    31. #Set the visits log of this virtual host

    32. access_log Logs/www.yejr.com.access.log Main;

    33. #If you visit/i mg /*, /js/*, /css/* resources, fetch local files directly without going through squid

    34.                                                                                                                                                                                                   . ^/(IMG | JS | CSS)/{

    35. root/data3/html;

    36. Expires 24h;

    37. } # -to ​​-/enable load balancing local/{proxy_pass http: // Proxy_redirect off; proxy_Set _Header Host $ Host ; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Location / {

    38.                                                                                               ’ ’ ’                             ‐ out ‐ ‐ ‐ ‐ ‐                                                                                                                                        off ;

    39.                                    proxy_set_header                  Host $host; X-Real-IP $remote_addr;

    40.                                 client_max_body_size 10m;

    41. ​ ​ ​ proxy_connect_timeout 90;#p#Page title #e#

    42.                                                                                                         ’ ’ ’ ’ ’ ’ 1 1 ‐ t t                                               I S S S S           ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐                            ;

    43.                                                     proxy_buffer_size         4k; 2k;
    44. B proxy_busy_buffers_size 64k;

    45. proxy_temp_file_write_size 64k;

    46. }

    47. #Set the address of nginx state

    48. nginxstatus {

    49. STUB_STATUS on;

    50. Access_ log on; t auth_basic "nginxstatus";
    51.                                                                                                                                                                                                                                                                         been been been been been been
      }

    52. }

    53. Copy code




Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development 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.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.