The most comprehensive Nginx introductory tutorial + Common configuration Resolution

Source: Internet
Author: User
Tags http 200 openssl parent directory sendfile xsl xsl file domian

Personal collation of information, reprint annotated source, thank you ~

nginx Introduction and Installation a simple configuration file Module Introduction Common Scenario Configuration Advanced Content reference materials

= = Nginx Introduction and Installation = =

Nginx is a free, open source, high-performance and lightweight HTTP server and reverse proxy server,

The performance is comparable to the IMAP/POP3 proxy server. Nginx is famous for its high performance, stability, rich function, simple configuration and low utilization of system resources.

Nginx surpasses Apache's high performance and stability, making it more and more Web sites that use Nginx as a Web server in China.

* Basic function

Process static files, index files, and automatic indexing;

Reverse proxy acceleration (no caching), simple load balancing and fault tolerance;

FastCGI, simple load balancing and fault tolerance;

Modular structure. Filters include gzipping, byte ranges, chunked responses, and Ssi-filter. In an SSI filter, multiple child requests to the same proxy or FastCGI are processed concurrently;

SSL and TLS SNI support;

* Advantages

Nginx is designed for performance optimization, performance is its most important consideration, the implementation of very focused on efficiency. It supports the kernel poll model, which can withstand high load, and reports indicate that it can support up to 50,000 concurrent connections.

Nginx as a load balancing server: Nginx can directly support Rails and PHP programs externally, and can support external services as an HTTP proxy server.

The nginx has a high stability. Other HTTP servers, when they encounter spikes in access, or when someone maliciously initiates a slow connection, are likely to cause the server to run out of physical memory for frequent swapping, losing response, and restarting the server.

For example, when Apache is up to more than 200 processes at the moment, the Web response is significantly slower. Nginx has adopted a phased resource allocation technique, which makes its CPU and memory occupancy rate very low.

Nginx official says it maintains 10,000 inactive connections, which only account for 2.5M of memory, and Nginx is better than lighthttpd in terms of stability.

Nginx supports hot deployment. It's very easy to start, and it's almost 7*24 uninterrupted, even if it's running for a few months and doesn't need to be restarted. You will also be able to upgrade the software version with uninterrupted service.

Nginx use C to write, whether it is the system resource cost or CPU efficiency is much better than Perlbal.

Installation of *nginx

Development of stable version: Nginx 0.8.X

Current stable version: Nginx 0.7.X

Stable version: Nginx 0.6.X

1) Pcre installation, support regular Expression http://www.pcre.org/# tar zxvf pcre-7.9.tar.gz # cd pcre-7.9 #./configure # make && make install 2 OpenSSL installation (optional), sites that support security protocols http://www.openssl.org/# tar ZXVF openssl-0.9.8l.tar.gz # cd openssl-0.9.8l #./config # Make & amp;& make install 3) Nginx installation # tar ZXVF nginx-0.7.64.tar.gz # cd nginx-0.7.64 Configure installation and do not install components:--with-module_name or--with Out-module_name #/configure--prefix=/usr/local/nginx/nginx8011--with-openssl=/usr/include/openssl--with-http_ Stub_status_module # make && make install directory structure: Conf config file HTML static page logs log file Sbin main program 4) Start #/usr/local/nginx/ngi Nx8011/sbin/nginx/Boot Startup parameters:-C </path/to/config> Specify a profile for Nginx to replace the default. -T does not run and only tests the configuration file. Nginx will check the correctness of the configuration file's syntax and attempt to open the file referenced in the configuration file. -V Displays the version of Nginx. -V Displays the version of Nginx, the compiler version, and the configuration parameters. Do not start, test profile only:/usr/bin/nginx-t-C ~/mynginx.conf 5) configuration from boot

= = A simple configuration file = =

#-----------------------------------Basic Module # used by users and groups user www www; # Specify the number of working processes worker_processes 1; # can use [Debug | info | notice | warn | error | crit] parameter #error_log logs/error.log; #error_log Logs/error.log Notice; # Specifies the path that the PID stores #pid logs/nginx.pid; #-----------------------------------Event Module Events {#每个worker的最大连接数 worker_connections 1024} #----------------------- ------------HTTP Module http {#包含一个文件描述了: MIME corresponding to different file suffixes, see case analysis include mime.types; #制定默认MIME类型为二进制字节流 Default_type Application/octet-stream; #指令 Access_log assigns paths, formats, and cache sizes. #access_log off; #开启调用Linux的sendfile (), providing file transfer efficiency sendfile on; #是否允许使用socket的TCP_NOPUSH或TCP_CORK选项 #tcp_nopush on; #指定客户端连接保持活动的超时时间, after this time, the server shuts down the connection. Keepalive_timeout 65; #设置gzip, compressed file #gzip on; #为后端服务器提供简单的负载均衡 upstream Apaches {server 127.0.0.1:8001; server 127.0.0.1:8002;} #配置一台虚拟机 server {listen 8012; server_ name localhost; Location/{Proxy_pass http://apaches;}} }

= = Module Introduction = =

Module Division:

#Core Core Modules

#Events Event Module

#HTTP HTTP Module

#Mail Mail Module

* Common components of core modules

User syntax: User user [group] default: Nobody nobody specifies that the Nginx worker process runs users, and the default is nobody account number. Error_log Syntax: error_log file [Debug | info | notice | warn | error | crit] Default: ${prefix}/logs/error.log set the location and level where the error log is stored. Include syntax: include file | * Default value: The none include directive also supports globally contained methods like the one below, including all files with a directory ending with ". conf": Include vhosts/*.conf; PID syntax: The PID file process ID stores files. You can use Kill-hup Cat/var/log/nginx.pid/to perform a configuration file reload on Nginx. Worker_processes Syntax: worker_processes number Default value: 1 Specifies how many worker processes. Nginx can use multiple worker processes.

* Common components of the event module

Worker_connections Syntax: worker_connections number can be calculated by worker_connections and worker_proceses maxclients:max_clients = Worker_processes * Worker_connections As a reverse proxy, max_clients is: max_clients = worker_processes * WORKER_CONNECTIONS/4, Multiple connections are established through the connection pool when the browser is accessed. Use syntax: used [kqueue | rtsig | epoll |/dev/poll | select | poll | eventport] If more than one event model is specified in./configure, you can set one to tell What kind of event model Nginx use. By default, Nginx will find the most appropriate event model for the system in./configure. The event model refers to the way Nginx handles connections.

Core components and variables for *http modules

Three scopes: HTTP, server, location server syntax: server {...} scope: HTTP configures a virtual machine. Location Syntax: location [=|~|~*|^~]/uri/{...} scope: Server configuration Access Path processing method. Listen syntax: Listen address:port [default [Backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bin D | SSL] Default value: Listen 80 Scope: server Specifies the listening port for the current virtual machine. Alias syntax: Alias File-path|directory-path; Scope: Location This directive sets the path used by the specified location. Note that it is similar to root, but does not change the root path of the file, only using the file system path root syntax: Root path default: Root HTML scope: HTTP, server, Location alias Specifies a directory that is accurate, root is the parent directory of the specified directory, and the parent directory contains a directory with the same name as the location named. Difference: location/abc/{alias/home/html/abc/} In this configuration, http://test/abc/a.html specifies/home/html/abc/a.html. This configuration can also be changed to location/abc/{root/home/html/} so that Nginx will find the/home/html/directory of the ABC directory, the results are the same. The other basic components of the HTTP module will be described in combination with the case. Variable: The value of the specified header inside the HTTP header, and the variable is converted to lowercase, such as $http _user_agent, $http _referer ... header information "your-strange-header:values" can pass $h Ttp_your_strange_header obtained. $arg _parameter $http _header $query _string = $args

* Common components of the Mail Module (abbreviated)

= = Common scene Configuration = =

1. Multiple server Configuration load Balancing

HTTP {include mime.types; Default_type application/octet-stream; sendfile on; keepalive_timeout; upstream Allserver { #ip_hash; Server 127.0.0.1:8083 down; Server 127.0.0.1:8084 weight=3; Server 127.0.0.1:8001; Server 127.0.0.1:8002 backup; server {listen 8012; server_name localhost; location/{Proxy_pass http://allserver;}}}

Ip_hash; The Ip_hash technology in Nginx can direct an IP request to the same backend, so that a client and a backend under this IP can establish a solid session

1.down indicates that the server before the single is temporarily not participating in the load

2.weight The default is 1.weight larger, the weight of the load will be greater.

3.backup: All other non-backup machines request backup machines when down or busy. So this machine will be the lightest pressure.

2. Through the phone client's header information or requested parameters forwarded to the directory

HTTP {include mime.types; Default_type application/octet-stream; sendfile on; keepalive_timeout; upstream Apaches {SE RVer 127.0.0.1:8001; Server 127.0.0.1:8002; } upstream Tomcats {server 127.0.0.1:8083; server 127.0.0.1:8084} server {listen 8012; server_name localhost; location /{set $ismob 0; # Note If the space after the IF ($http _chip ~* "(NOKIA3500) | ( NOKIA3200) "{set $ismob 1; Proxy_pass http://apaches} if ($http _chip ~*" (NOKIA3500) | ( NOKIA3200) "{set $ismob 1; Proxy_pass http://tomcats} if ($ismob = 0) {root/usr/local/nginx/nginx8012/html;}} Location ~*/rewrite/testxid.jsp {if ($arg _xid = "13800138000") {rewrite ^ (. *) $ http://192.168.0.190:8084/testSID.jsp b Reak; } } } }

1, regular expression matching, where:

= completely equal;

~ to match case sensitivity;

~* matching for case-insensitive case;

!~ and!~* are case insensitive and case-insensitive mismatches, respectively.

2, file and directory matching, including:

-F and!-f are used to determine whether a file exists;

-D and!-d are used to determine whether a directory exists;

-E and!-e are used to determine whether a file or directory exists;

X and!-x are used to determine whether the file is executable.

if (-D $request _filename) {...}

Where the regular expression will appear:

1.location ~*/. (gif|jpg|png|swf|flv) ${...}

2.rewrite ^ (. *) $/nginx-ie/$1 break;

Regular expressions are examples of:

1. Multi-Directory conversion parameters ABC.DOMIAN.COM/SORT/2 => abc.domian.com/index.php?act=sort&name=abc&id=2

if ($host ~* (. *)/.domain/.com) {

Set $sub _name $;

Rewrite ^/sort//(/d+)//?$/index.php?act=sort&cid= $sub _name&id=$1 last;

}

2. Directory Swap/123456/xxxx->/xxxx?id=123456

Rewrite ^/(/d+)/(. +)//$2?id=$1 last;

3. Anti-Theft Chain

HTTP {include mime.types; Default_type application/octet-stream; sendfile on; keepalive_timeout; server {listen 8012; server_name localhost; Location/{root HTML;} location ~* ^.+/. (Gif|jpg|png|swf|flv|rar|zip) $ {valid_referers None blocked server_names http://localhost baidu.com; if ($invalid _ Referer) {rewrite ^/html/50x.html;}} } }

4. Access control: Authentication, restricting IP

HTTP {include mime.types; Default_type application/octet-stream; sendfile on; keepalive_timeout; upstream Tomcats {SE RVer 127.0.0.1:8083; Server 127.0.0.1:8084; server {listen 8012; server_name localhost; location/{allow 192.168.4.8; deny all; Auth_basic "index"; auth_basic_us Er_file.. /HTPASSWD; Proxy_pass Http://tomcats; } } }

cp/usr/local/apache/apache8001/bin/htpasswd/usr/local/bin/

/usr/local/bin/htpasswd-c htpasswd Root

5. View the running status of the Nginx

HTTP {include mime.types; Default_type application/octet-stream; sendfile on; keepalive_timeout; upstream Apaches {SE RVer 127.0.0.1:8001; Server 127.0.0.1:8002; } upstream Tomcats {server 127.0.0.1:8083; server 127.0.0.1:8084} server {listen 8012; server_name localhost; location /{Proxy_pass Http://tomcats} location/nginxstatus {stub_status on; Access_log off; Auth_basic "Nginxstatus"; auth_b Asic_user_file.. /HTPASSWD; } } }

= = Advanced Content = =

1. View the running status of the Nginx

Active connections:364

Server accepts handled requests

5477919 5477919 17515830

Reading:10 writing:26 waiting:328

The meaning is as follows:

Active connections– the number of active connections currently being processed by Nginx.

Serveraccepts handled requests--a total of 5,477,919 connections were made, 5,477,919 handshakes were successfully created (no failure in the middle), and 17,515,830 requests were processed (on average 3.2 digits per handshake) It is requested).

Reading--The number of Header information that Nginx reads to the client.

Writing-The number of Header information that the Nginx returns to the client.

Waiting-When keep-alive is turned on, this value equals active-(reading + writing), meaning that Nginx has finished processing the resident connection waiting for the next request instruction.

2. Case study:

Changing the Web server from Apache to Nginx brings unexpected problems. Multiple page display modules show "Loading ..." and then pause, using Firebug Debug front-end, XSL file parsing failed. But loading is the normal state of HTTP 200.

Continue debugging with Firebug, find the HTTP response header in the XSL file download,

Content-type is Oct/stream, and in the original Apache, is text/xml, so modify/etc/nginx/mime.types file. Add the XSL extension to the XML group. Problem solving.

3. Through the system of signal control Nginx

To load a new configuration with a signal

Smooth upgrade to new binary code

4. Limit download rate and concurrent number using Nginx

Limit_zone Limit_conn Limit_rate

5. Use Nginx for address forwarding

Rewrite

The difference between last and break in Nginx rewrite: http://blog.sina.com.cn/s/blog_4b01279a0100hd4c.html

Analysis of 6.Nginx Internals:nginx source code and internal mechanism

http://blog.zhuzhaoyuan.com/2009/09/nginx-internals-slides-video/

= = Reference = =

Nginx Chinese Documents:

Http://wiki.nginx.org/NginxChs

Server System Architecture Analysis log:

http://www.sudone.com/

Use Nginx to increase Web Access speed:

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

nginx Introduction and Installation a simple configuration file Module Introduction Common Scenario Configuration Advanced Content reference materials

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.