== Introduction and Installation ==
Nginx is a free, open source, lightweight and high-performance HTTP server and reverse proxy server,
Its performance and IMAP / POP3 proxy server rather. Nginx its high performance, stability, feature-rich, simple to configure and less system resources known.
Beyond Nginx Apache's performance and stability, the domestic use Nginx as a Web server site more and more.
*basic function
Static files, index files, and automatic indexing;
Accelerated reverse proxying (without caching), simple load balancing and fault tolerance;
FastCGI, simple load balancing and fault tolerance;
The modular structure. Filter comprises gzipping, byte ranges, chunked responses, and SSI-filter. At the SSI filter, to the same or a plurality of sub FastCGI proxy request concurrent processing;
SSL and TLS SNI support;
*Advantage
Nginx designed for performance optimization and development, performance is the most important consideration, very focused on efficiency achieved. It supports kernel Poll model, able to withstand the test of high load, it has been reported that can support up to 50,000 concurrent connections.
Nginx as a load balancing server: Nginx either directly support Rails and PHP programs inside in foreign service, can also support as an HTTP proxy server in foreign service.
Nginx with high stability. Other HTTP server, when faced with the peak access, or someone maliciously initiated a slow connection, it is likely to cause the server to run out of physical memory frequent exchange loss of response, only to restart the server.
For example, once the current apache process to more than 200, web response speed is obviously very slow. The Nginx has taken a phased resource allocation technology, making its CPU and memory usage rate is very low.
nginx officials said no activity to keep 10,000 connections, it accounts for only 2.5M of memory, in terms of stability, nginx than lighthttpd better.
Nginx supports hot deployment. It's particularly easy to start, and can be done almost 7 * 24 uninterrupted operation, even running a few months does not require a reboot. You can also in the case of uninterrupted service, the software version upgrade.
Nginx using C to write, whether it is the system resource overhead or CPU efficiency than Perlbal much better.
* Nginx installation
Development of stable version: Nginx 0.8.X
The current stable version: Nginx 0.7.X
History stable version: Nginx 0.6.X
- 1) pcre installation, support for regular expressions
http://www.pcre.org/
# tar zxvf pcre-7.9.tar.gz
# cd pcre-7.9
#./configure
# make && make install
- 2) openssl site installation (optional), support for security protocols
http://www.openssl.org/
# tar zxvf openssl-0.9.8l.tar.gz
# cd openssl-0.9.8l
#./config
# make && make install
- 3) nginx mounting
# tar zxvf nginx-0.7.64.tar.gz
# cd nginx-0.7.64
Installation and mounting assembly configuration is not: - with-MODULE_NAME or --without-MODULE_NAME
# ./configure --prefix=/usr/local/nginx/nginx8011 --with-openssl=/usr/include/openssl --with-http_stub_status_module
# make && make install
Directory Structure:
- conf configuration file
- html static page
- logs log file
- sbin main program
- 4) Start
# /usr/local/nginx/nginx8011/sbin/nginx //启动
Startup parameters:
-c </ path / to / config> specify a profile for Nginx, instead of the default.
-t is not running, but only to test the profile. nginx will check the correctness of the syntax of the configuration file and try to open the file in your profile referenced to.
-v display nginx version.
-V display nginx version, compiler version and configuration parameters.
Does not start, only the test configuration file: / usr / bin / nginx -t -c ~ / mynginx.conf
- 5) since the launch configuration
== Profile ==
# ----------------------------------- basic module
# 使用的用户和组
user www www;
# 指定工作进程数
worker_processes 1;
# 可以使用 [ debug | info | notice | warn | error | crit ] 参数
#error_log logs/error.log;
#error_log logs/error.log notice;
# 指定 pid 存放的路径
#pid logs/nginx.pid;
# ----------------------------------- event module
events {
#每个worker的最大连接数
worker_connections 1024;
}
# ----------------------------------- HTTP module
http {
#包含一个文件描述了:不同文件后缀对应的MIME,见案例分析
include mime.types;
#制定默认MIME类型为二进制字节流
default_type application/octet-stream;
#指令 access_log 指派路径、格式和缓存大小。
#access_log off;
#开启调用Linux的sendfile(),提供文件传输效率
sendfile on;
#是否允许使用socket的TCP_NOPUSH或TCP_CORK选项
#tcp_nopush on;
#指定客户端连接保持活动的超时时间,在这个时间之后,服务器会关掉连接。
keepalive_timeout 65;
#设置gzip,压缩文件
#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 Description ==
Module division:
- #Core core module
- #Events event module
- #HTTP HTTP module
- #Mail Mail module
* The core module of common components
user
Syntax: user user [group]
Default value: nobody nobody
Nginx Worker specified user process runs, the default is nobody account.
error_log
语法: error_log file [ debug | info | notice | warn | error | crit ]
Default: $ {prefix} /logs/error.log
Develop storage location and level of the error log.
include
Syntax: include file | *
Default value: none
include the following configuration instructions also support the same way as the global comprising, for example comprising a directory to all ".conf" end of the file:. include vhosts / * conf;
pid
Syntax: pid file
Process id file storage. You can use kill -HUP cat /var/log/nginx.pid/ Nginx configuration files to be reloaded.
worker_processes
Syntax: worker_processes number
Default: 1
Specifies the number of processes work. nginx can use multiple worker processes.
* Event module of common components
[python] view plain copy print?
worker_connections
语法:worker_connections number
Can be calculated by worker_connections maxclients and worker_proceses: max_clients = worker_processes * worker_connections
As a reverse proxy, max_clients as: max_clients = worker_processes * worker_connections / 4, as it will establish multiple connections through a connection pool when the browser visits.
use
语法:use [ kqueue | rtsig | epoll | /dev/poll | select | poll | eventport ]
If more than one event model is specified at the time of ./configure, you can set one to tell nginx event which model to use. By default, nginx will identify the most suitable event model system when ./configure.
Nginx event model is a method of handling the connection.
* Core components and variables HTTP modules
Three scopes: http, server, location
server
Syntax: server {...}
Scope: http
Configuring a virtual machine.
location
Syntax: location [= | ~ | ~ * | ^ ~] / uri / {...}
Scope: server
Access path configuration processing method.
listen
语法: listen address:port [ default [ backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind | ssl ]
Default value: listen 80
Scope: server
Specifies the listening port of the current virtual machine.
alias
Syntax: alias file-path | directory-path;
Scope: location
The instruction set used for the path designated location. Note that it is similar with the root, but does not change the root file only using file system path
root
Syntax: root path
Default value: root html
Scope: http, server, location
alias specified directory is accurate, root directory is specified in the parent directory and the parent directory to the directory location of the same name containing the specified name.
the difference:
location /abc/ {
alias /home/html/abc/;
}
In this configuration, http: //test/abc/a.html the designation is /home/html/abc/a.html. This configuration can also be changed
location /abc/ {
root /home/html/;
}
Thus, you will find Nginx abc directory under / home / html / directory, and the result is the same.
Other basic components of HTTP modules will be introduced in conjunction with the case.
variable:
HEADER value of a specific HTTP header inside, to lower case variables, such as $ http_user_agent, $ http_referer ... header information "YOUR-STRANGE-HEADER: values" $ http_your_strange_header can be obtained.
$arg_PARAMETER
$http_HEADER
$query_string = $args
* Common components Mail Module (slightly)
== Common Scenario Configuration ==
1. Multi-server configuration Load Balancing
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
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; ip_hash nginx in the art can request an ip is directed to the same backend, a client in this way the ip and a rear end of the session will be able to establish a solid
- 1.down a front single server is temporarily not participate in load
- 2.weight default 1.weight greater, the greater the weight load of weight.
- 3.backup: all other backup machine down or non-busy times, requests backup machine. So this machine will be the lightest pressure.
2. forwarded to the head without directory information by phone or client request parameters
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream apaches {
server 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;
# 注意if后的空格
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 break;
}
}
}
}
- 1, regular expression matching, in which:
= Completely equal;
~ Is a case-sensitive match;
~ * Is a case-insensitive match;
! ~ And! ~ *, And mismatches are case-insensitive match is not case-sensitive.
- 2, matching files and directories, including:
! -F -f and used to determine whether there is a file;
! -D -d used and whether or not directory;
! -E -e and used to determine whether there is a file or directory;
-x and! -x is used to determine whether an executable file.
if (-d $request_filename){ ... }
What place will the regular expression:
1.location ~* /.(gif|jpg|png|swf|flv)${...}
2.rewrite ^(.*)$ /nginx-ie/$1 break;
Regular expressions example:
1. Multiple directory transformed into parameters abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2
if ($host ~* (.*)/.domain/.com) {
set $sub_name $1;
rewrite ^/sort//(/d+)//?$ /index.php?act=sort&cid=$sub_name&id=$1 last;
}
2. Contents of exchange / 123456 / xxxx -> / xxxx id = 123456?
rewrite ^/(/d+)/(.+)/ /$2?id=$1 last;
3. anti-hotlinking
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
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, IP restrictions
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream tomcats {
server 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_user_file ../htpasswd;
proxy_pass http://tomcats;
}
}
}
cp /usr/local/apache/apache8001/bin/htpasswd /usr/local/bin/
/usr/local/bin/htpasswd -c htpasswd root
5. Check the operating state of Nginx
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream apaches {
server 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_basic_user_file ../htpasswd;
}
}
}
== Advanced content ==
1. Check the operating status of Nginx
Active connections: 364
server accepts handled requests
5477919 5477919 17515830
Reading: 10 Writing: 26 Waiting: 328
Meaning as follows:
active connections - the number of active connections Nginx is currently being processed.
serveraccepts handled requests - handled a total of 5,477,919 connections, successfully created 5,477,919 handshake (with no proof of failure), it handled a total of 17,515,830 requests (an average of 3.2 each handshake deal with data requests).
reading - nginx read Header information on the number of clients.
writing - nginx returned to the Header count information for the client.
waiting - open case keep-alive, and this value is equal to active - (reading + writing), meaning that the processing has been completed Nginx reside next waiting connection time request command.
2. Case Study:
After the change by the apache web server is nginx, has brought unexpected problems. Display module to display multiple pages XSL file parsing failed "is loading ..." and then has been stopped, use FireBug debugger front-end, but is loaded HTTP normal state 200.
Continue to use FireBug debugging and found that when the XSL file download HTTP response header,
Content-Type is oct / stream, but in the original apache in a text / xml, then modify /etc/nginx/mime.types file. The extension of the XSL added xml group problem solving.
The control system via a signal Nginx
Use the signal to load the new configuration
Smooth upgrade to the new binary code
4. Nginx rate and limit the number of concurrent downloads
limit_zone limit_conn limit_rate
5. forwarding address for Nginx
rewrite
The difference between last and break the nginx rewrite in: http://blog.sina.com.cn/s/blog_4b01279a0100hd4c.html
6.Nginx Internals: Nginx source code analysis of the internal mechanism
http://blog.zhuzhaoyuan.com/2009/09/nginx-internals-slides-video/
== References ==
Nginx Chinese document :
http://wiki.nginx.org/NginxChs
Server log analysis system architecture:
http://www.sudone.com/
Use Nginx increase site access speed:
http://www.ibm.com/developerworks/cn/web/wa-lo-nginx/