Use Nginx to improve website access speed

Source: Internet
Author: User
Tags netcraft

About Nginx

Nginx ("Engine X") is a high-performance HTTP and reverse proxy server and also a IMAP/POP3/SMTP proxy server. Nginx was developed by Igor Sysoev, the second-most visited rambler.ru site in Russia, which has already run more than 2.5 of the site. Igor release the source code in the form of a BSD-like license. Although still beta, Nginx has been known for its stability, rich feature set, sample configuration files, and low system resource consumption.

According to the latest issue of the NetCraft survey (June 08), more than 2 million of the hosts already use Nginx, a number that exceeds the other lightweight HTTP server LIGHTTPD, ranked fourth, and has grown rapidly. Here are the top reports for this report:

Product Number of sites
Apache 84,309,103
Iis 60,987,087
Google GFE 10,465,178
Unknown 4,903,174
Nginx 2,125,160
Oversee 1,953,848
Lighttpd 1,532,952

For more detailed information on this report, please see the link below:

http://survey.netcraft.com/Reports/200806/

Is the comparison of the number of sites using Nginx and lighttpd in the last few months

Figure 1. Compare the number of sites using Nginx and lighttpd in the last few months

Things to know before using Nginx
    1. Currently the official Nginx does not support Windows, you can only include Linux, UNIX, BSD system installation and use;
    2. Nginx itself is only an HTTP and reverse proxy server, it can not be like Apache by installing various modules to support different page scripts, such as PHP, CGI, etc.;
    3. Nginx supports simple load balancing and fault tolerance;
    4. Supports functions as basic HTTP servers, such as logs, compression, Byte ranges, Chunked responses, SSL, virtual hosts, and more.
Installing Nginx under Linux

To ensure a more flexible configuration using regular expressions in Nginx, it is necessary to determine if the system has the PCRE (Perl Compatible Regular Expressions) package installed before installation. You can download the latest Pcre source package to ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/and download the compile and install Pcre package using the command below:

# wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.7.tar.gz# tar zxvf pcre-7.7.tar.gz# cd pcre-7.7#. /configure# make# make Install

The next installment Nginx,nginx generally has two versions, is the stable version and the development edition, you can choose one of these two versions according to your goal, below is the detailed step which installs the Nginx to the/opt/nginx directory:

# wget http://sysoev.ru/nginx/nginx-0.6.31.tar.gz# tar zxvf nginx-0.6.31.tar.gz# cd nginx-0.6.31#./configure-- with-http_stub_status_module–prefix=/opt/nginx# make# make Install

The parameters --with-http_stub_status_module are to enable Nginx's Nginxstatus function, which is used to monitor the current state of Nginx.

After successful installation, there are four subdirectories in the/opt/nginx directory: conf, HTML, logs, Sbin. Where nginx configuration file is stored in Conf/nginx.conf,nginx only one program file located in the Sbin directory of nginx files. Ensure that the system's 80 port is not occupied by other programs, run the Sbin/nginx command to start Nginx, open the browser to access this machine's IP, if the browser appears Welcome to nginx! Indicates that Nginx is installed and running successfully.

Common Nginx parameters and control program operation parameters

Nginx installation only a program file, itself does not provide a variety of management programs, it is the use of parameters and system signaling mechanism of the NGINX process itself control. Nginx parameters include the following:

- c <path_to_config>: Use the specified configuration file instead of the nginx.conf in the Conf directory.

- T: The test configuration file is correct and it is important to detect if a modified configuration file has a syntax error when the configuration needs to be reloaded at run time.

- v: Displays the Nginx version number.

- v: Displays the version number of the Nginx as well as the compilation environment information and compile-time parameters.

For example, if we want to test whether a configuration file is written correctly, we can use the following command

Sbin/nginx–t–c conf/nginx2.conf
Control of Nginx via signal

Nginx supports the signals in the following table:

Signal name function Description
term, INT Close the program quickly to abort the request that is currently being processed
QUIT Close the program after processing the current request
HUP Reload the configuration and open a new worker process, close the process, and this action will not interrupt the request
USR1 Reopen the log file for switching logs, such as generating a new log file every day
USR2 Smooth Upgrade Executable Program
WINCH Gracefully close the worker process

There are two ways to control nginx through these signals, the first is through the logs directory Nginx.pid view the current operation of the Nginx process ID, through kill – XXX <pid> to control Nginx, where XXX is the signal name listed in the table above. If you have only one Nginx process in your system, you can do so by killall command, such as running killall – s HUP nginx to let Nginx reload the configuration.

Configure Nginx

First look at an actual configuration file:

 User nobody;# work process of the main worker_processes 4;# working process, and the CPU is generally equivalent to the number of cores #error_log logs/error.log;  #error_log Logs/error.log Notice;  #error_log Logs/error.log Info;  #pid Logs/nginx.pid; events {use Epoll; the best performing event mode under #Linux worker_connections 2048;# each worker process allows maximum simultaneous connections} HTTP {include M     Ime.types;     Default_type Application/octet-stream; #log_format Main ' $remote _addr-$remote _user [$time _local] $request ' # ' "$status" $body _bytes_sen     T "$http _referer" ' # ' "$http _user_agent" "$http _x_forwarded_for";     #access_log off;     Access_log logs/access.log;# log file name sendfile on;     #tcp_nopush on;     Tcp_nodelay on;     Keepalive_timeout 65;         Include gzip.conf;  # configuration information for all background 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;         } server {listen; #HTTP port server_name localhost;         CharSet Utf-8;  #access_log Logs/host.access.log Main;  Location ~ ^/nginxstatus/{stub_status on; #Nginx status monitoring configuration Access_log off;  } Location-^/(Web-inf)/{deny all; } location ~ \. (htm|html|asp|php|gif|jpg|jpeg|png|bmp|ico|rar|css|js| zip|java|jar|txt|flv|swf|mid|doc|ppt|xls|pdf|txt|mp3|wma     ) $ {Root/opt/webapp;         Expires 24h;         } location/{Proxy_pass http://tomcats;# reverse proxy include proxy.conf;         } error_page 404/html/404.html;         # REDIRECT Server error pages to the static page/50x.html # Error_page 502 503/html/502.html;         Error_page 504/50x.html;         Location =/50x.html {root html; }     }  }
Nginx Monitoring

Above is an example of a real site configuration, where gray text is a configuration description. In the above configuration, we first defined a location ~ ^/nginxstatus/, so that through the http://localhost/NginxStatus/can monitor the operation of Nginx information, the content is as follows:

Active CONNECTIONS:70 Server accepts handled requests 14553819 14553819 19239266 reading:0 writing:3 waiting:67

The contents of the Nginxstatus display are as follows:

    • Active connections– the number of active connections currently being processed by Nginx.
    • Server accepts handled requests-a total of 14,553,819 connections were processed, 14,553,819 handshakes were successfully created (proving that there was no failure in the middle), and a total of 19,239,266 requests were processed (averaging 1 per handshake). 3 data requests).
    • Reading--The number of Header information that Nginx reads to the client.
    • Writing--The number of Header information returned to the client by Nginx.
    • Waiting--when keep-alive is turned on, this value is equal to active-(reading + writing), meaning that Nginx has processed the host connection that is waiting for the next request instruction.
Static file Processing

With regular expressions, we can let Nginx identify various static files, such as all requests under the images path can be written as:

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

The following configuration defines the request handling for several file types.

Location ~ \. (Htm|html|gif|jpg|jpeg|png|bmp|ico|css|js|txt) $ {    Root/opt/webapp;    Expires 24h;}

For example slices, static HTML files, JS script files and CSS style files, and so on, we hope that Nginx directly processing and return to the browser, this can greatly improve the speed of web browsing. So for this type of file we need to specify the path of the file through the root instruction, and because this kind of file is not often modified, expires control its cache in the browser by instruction to reduce unnecessary requests. expiresdirectives can control the headers of "Expires" and "Cache-control" in HTTP replies (play a role in controlling page caching). You can write Expires using a format such as the following:

Expires 1 January, 1970, 00:00:01 gmt;expires 60s;expires 30m;expires 24h;expires 1d;expires max;expires off;
Dynamic page Request Processing

Nginx itself does not support the current popular JSP, ASP, PHP, PERL and other dynamic pages, but it can be sent through the reverse proxy request to the backend server, such as Tomcat, Apache, IIS, etc. to complete the dynamic page request processing. In the previous configuration example, we first defined some static file requests that were processed directly by Nginx, and all other requests were routed to the backend server via the proxy_pass instruction (Tomcat in the example above). The simplest proxy_pass usage is as follows:

Location/{    proxy_pass        http://localhost:8080;    Proxy_set_header  x-real-ip  $remote _addr;}

Instead of using the cluster, we sent the request directly to the TOMCAT service running on port 8080 to complete the request processing like JSP and Servlet.

When the amount of page access is very large, often need multiple application servers to jointly assume the dynamic page execution, then we need to use the cluster's architecture. Nginx upstream defines a cluster of servers by instruction, in the first complete example we define a cluster called Tomcats, which includes three servers with a total of 6 Tomcat services. The wording of the Proxy_pass directive became:

Location/{    proxy_pass        http://tomcats;    Proxy_set_header  x-real-ip  $remote _addr;}

In nginx cluster configuration, Nginx uses the simplest average allocation rule to assign requests to each node in the cluster. Once a node fails, or when it is restarted, Nginx handles the change of State very promptly to ensure that the user's access is not affected.

Summarize

Although the entire package is only more than 500 K, but very little, perfectly formed. Nginx provides a variety of functional modules, combined with these modules can complete a variety of configuration requirements, such as: compression, anti-theft chain, cluster, FastCGI, streaming media server, Memcached support, URL rewriting and so on, more critical is Nginx has Apache and other The HTTP server does not match the high performance. You can even improve the speed of your website by introducing Nginx in front of you without changing the original site's architecture.

This article simply introduces Nginx installation and common basic configuration and use, more information about Nginx Please read the reference resources behind the article. Thank you very much for my friend-Chen Lei ([email protected]), he has been doing the Nginx Chinese wiki (http://wiki.codemongers.com/NginxChs), but also he introduced me such a good piece of software.

If your site is running under Linux, you should try Nginx if you do not use some very complex features that you can not do with Nginx.

Use Nginx to improve website access speed (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.