Use Nginx to speed up Website access

Source: Internet
Author: User
Tags netcraft
This article describes how to install a high-performance HTTP server, Nginx, on a Linux system and use Nginx to speed up Website access without changing the original website structure.

Nginx Introduction

Nginx("Engine x") is a high-performance HTTP and reverse proxy server and an IMAP/POP3/SMTP proxy server. Nginx was developed by the Rambler.ru site with the highest access volume in Russia as Igor Sysoev. It has been running on this site for more than two and a half years. Igor publishes source code in the form of a class BSD license. Despite being a beta version, Nginx is well known for its stability, rich feature sets, sample configuration files, and low system resource consumption.

According to the latest NetCraft survey (March June), more than 2 million of hosts have used Nginx, and this number exceeds the other lightweight HTTP server lighttpd, ranking fourth, and growing rapidly. The first few reports of this report are as follows:

Product Website count
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 details about this survey report, see the following link:

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

Compare the number of websites using Nginx and lighttpd in recent months.

Figure 1. Comparison of the number of websites using Nginx and lighttpd in recent months

Precautions before using Nginx

  1. Currently, Nginx does not support Windows. You can only install and use Nginx on Linux, UNIX, and BSD systems;
  2. Nginx is only an HTTP and reverse proxy server. It cannot support different page Scripts like Apache by installing various modules, such as PHP and CGI;
  3. Nginx supports Simple load balancing and fault tolerance;
  4. Supports basic HTTP server functions, such as logs, compression, Byte ranges, Chunked responses, SSL, and virtual hosts.

Install Nginx in Linux

To make sure that you can use Regular Expressions in Nginx for more flexible configuration, You need to determine whether the PCRE (Perl Compatible Regular Expressions) package is installed in the system before installation. You can go to the ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ to download the latest PCRE source package, use the following command to download the compilation and installation of PCRE package:

# 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

 

Next, install Nginx. Nginx generally has two versions: stable version and development version. You can select one of these two versions for your purpose, the following describes how to install Nginx in 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

 

Parameters--with-http_stub_status_moduleTo enable nginx's NginxStatus function, it is used to monitor the current status of Nginx.

After the installation is successful, the/opt/nginx directory contains four subdirectories: conf, html, logs, and sbin. The Nginx configuration file is stored in conf/nginx. conf. Nginx only has one program file in the nginx file under the sbin directory. Make sure that port 80 of the system is not occupied by other programs. Run the sbin/nginx command to start Nginx and open the browser to access the IP address of the machine. If the browser displays Welcome to nginx! Nginx has been installed and runs successfully.

Common Nginx parameters and Control

Program running parameters

After Nginx is installed, there is only one program file, which does not provide various management programs. It uses parameters and system signal mechanisms to control the Nginx process itself. Nginx parameters include the following:

-C<Path_to_config>: Use the specified configuration file instead of nginx. conf In the conf directory.

-T: Test whether the configuration file is correct. This command is very important when you need to re-load the configuration during running. It is used to detect whether the modified configuration file has syntax errors.

-V: Displays the nginx version number.

-V: Displays the nginx version number, the compilation environment information, and the parameters during compilation.

For example, to test whether a configuration file is correctly written, run the following command:

sbin/nginx – t – c conf/nginx2.conf

 

Control Nginx by Signal

Nginx supports the following signals:

Signal name Role description
TERM, INT Close the program and stop the request being processed.
QUIT Close the program after processing the current request
HUP Reload the configuration, start a new working process, and close the process. This operation will not interrupt the request.
USR1 Re-open the log file to switch logs. For example, a new log file is generated every day.
USR2 Smooth upgrade of executable programs
WINCH Close the Working Process with ease

 

There are two ways to control Nginx through these signals. The first is to view the ID of the currently running nginx process through Nginx. pid in the logs directory.kill – XXX <pid>To control Nginx, where XXX is the signal name listed in the above table. If your system has only one Nginx process, you can also usekillallCommand to complete, such as runningkillall – s HUP nginxTo let Nginx reload the configuration.

Configure Nginx

First, let's look at an actual configuration file:

User nobody; # worker process owner worker_processes 4; # Number of worker processes, which is generally the same as the number of CPU 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; # worker_connections 2048, the best-performing event Mode in Linux; # maximum number of concurrent connections allowed by each worker process} http {include mime. types; default_type application/octet-stream; # log_format main '$ remote_addr-$ remote_user [$ time_local] $ request '# '"$ Status" $ body_bytes_sent "$ 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 of all backend servers in the cluster upstream effecats {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: 8 081 weight = 10; server 192.168.0.13: 8080 weight = 10; server 192.168.0.13: 8081 weight = 10;} server {listen 80; # 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 24 h;} location/{proxy_pass http: // invalid ATS; # 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 500 x.html; location =/50x.html {root html ;}}}

 

Nginx monitoring

The above is a configuration instance of the actual website, where the gray text shows the configuration instructions. In the above configuration, we first define a location ~ ^/NginxStatus/. In this way, the Nginx running information can be monitored through http: // localhost/NginxStatus/. The displayed content is as follows:

Active connections: 70 server accepts handled requests 14553819 14553819 19239266 Reading: 0 Writing: 3 Waiting: 67 

 

The content displayed in NginxStatus is as follows:

  • Active connections-number of active connections currently being processed by Nginx.
  • Server accepts handled requests -- 14553819 connections are processed in total, and 14553819 handshakes are created successfully (proving that there is no failure in the middle ), A total of 19239266 requests are processed (an average of 1.3 Data requests are processed in each handshake ).
  • Reading -- number of headers that nginx reads to the client.
  • Writing -- number of headers that nginx returns to the client.
  • Waiting -- When keep-alive is enabled, this value is equal to active-(reading + writing), meaning Nginx has processed the resident connection waiting for the next request command.

Static File Processing

Through regular expressions, Nginx can identify various static files. For example, all requests in the images path can be written as follows:

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

 

The following configuration defines several file-type request processing methods.

location ~ \.(htm|html|gif|jpg|jpeg|png|bmp|ico|css|js|txt)$ {    root /opt/webapp;    expires 24h;}

 

For examples, static HTML files, js script files, and css style files, we hope Nginx can directly process and return them to the browser, which can greatly speed up Web browsing. Therefore, for such files, we need to use the root command to specify the file storage path. because such files are not often modifiedexpiresCommand to control its cache in the browser to reduce unnecessary requests.expiresCommands can Control the header labels of "Expires" and "Cache-Control" in the HTTP Response (to Control the page Cache ). You can use the following format to write Expires:

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 does not support popular dynamic pages such as JSP, ASP, PHP, and PERL, but it can send requests to backend servers through reverse proxy, for example, Tomcat, Apache, and IIS can process dynamic page requests. In the preceding configuration example, after defining some static file requests that are directly processed by Nginx, all other requests are sent to the backend server through the proxy_pass command (Tomcat is used in the preceding example ). Simplestproxy_passThe usage is as follows:

location / {    proxy_pass        http://localhost:8080;    proxy_set_header  X-Real-IP  $remote_addr;}

 

Instead of using a cluster, we send requests directly to the Tomcat service running on port 8080 to process requests similar to JSP and Servlet.

When the page traffic is very large, multiple application servers are often required to perform operations on dynamic pages. In this case, we need to use the cluster architecture. NginxupstreamCommand to define a server cluster. In the previous complete example, we defined a cluster named tomcats, which contains six Tomcat services for three servers. The proxy_pass command is written as follows:

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 allocate requests to each node in the cluster. Once a node fails or becomes effective again, Nginx will handle changes in the status in a timely manner to ensure that user access is not affected.

Summary

Although the entire package is only over five hundred K, the sparrow is small and dirty. Nginx provides a wide range of functional modules, including compression, anti-leeching, cluster, FastCGI, streaming media server, Memcached support, and URL rewriting, more importantly, Nginx has high performance that is unmatched by Apache and other HTTP servers. You can even introduce Nginx at the front end to speed up Website access without changing the architecture of the original website.

This article only briefly introduces Nginx installation and common basic configuration and usage. For more information about Nginx, please read the reference resources later in this article. Here I would like to thank my friend Chen Lei (chanix@msn.com), who has been working on Nginx's Chinese WIKI (http://wiki.codemongers.com/NginxChs) And he introduced me to such a good software.

If your website is running in Linux, if you have not used some very complex functions and are sure that Nginx cannot be completed, try Nginx.

References

Learning

  • Check the Nginx English site.

  • Refer to the Nginx Chinese WIKI.
  • Refer to the Nginx English WIKI.
  • Another lightweight HTTP server, lighttpd.

Obtain products and technologies

  • Download the latest Nginx version.

  • Download PCRE.

This article from http://www.ibm.com/developerworks/cn/web/wa-lo-nginx/

If you want to configure the support for ASP. NET, refer to nginx + mono 2.0 in Ubuntu to support asp.net.

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.