Nginx common application Technical Guide [NginxTips]

Source: Internet
Author: User
[Preface]: This technical guide aims to popularize the use of NGINX in China and help you understand and master some NGINX usage skills. Many tips in this guide come from questions asked by friends on the Internet, at work, or on the Internet. Here, I would like to express my gratitude and greetings to those who are willing to share this online experience! You and I are welcome to enrich this technical guide.

[Preface ]:
This technical guide aims to popularize the use of NGINX in China and help you understand and master some NGINX usage skills more conveniently.

Many tips in this guide come from questions asked by friends on the Internet, at work, or on the Internet.

Thank you! You are welcome to enrich this technical guide and provide better suggestions!

I. Basic Nginx knowledge
1. Introduction
Nginx ("engine x") is a high-performance HTTP and reverse proxy server, and is also an IMAP/POP3/SMTP proxy server.

Server. Nginx is developed by the Rambler.ru site, where Igor Sysoev is the second highest traffic in Russia. It is already running on this site.

Over two and a half years. Igor publishes source code in the form of a class BSD license. Although it is still a test version, Nginx has

It is well known for its stability, rich feature sets, sample configuration files, and low system resource consumption.
For more information, see the official wiki: http://wiki.codemongers.com/

2. Advantages of Nginx
As an HTTP server, nginx has the following basic features:
1) process static files, index files, and automatic indexes; enable file descriptor buffering.
2) Non-Cache reverse proxy acceleration, simpleServer Load balancerAnd fault tolerance.
3) FastCGI, simple load balancing and fault tolerance.
4) Modular structure. Including gZipPing, Byte ranges, chunkEdResponses, and SSI-filter. If

If FastCGI or another Proxy Server Processes multiple SSI in a single page, the processing can run in parallel without waiting for each other.
5) supports SSL and tls sni.

Nginx is designed for performance optimization. performance is the most important consideration, and efficiency is very important in implementation. It supports the kernel Poll model.

According to the high load test, the report shows that up to 50,000 concurrent connections are supported.

Nginx has high stability. When other HTTP servers encounter access peaks or maliciously initiate slow connections

This can cause frequent exchanges and responses when the physical memory of the server is exhausted. You can only restart the server. For example, once apache reaches the 200

The web response speed is obviously very slow. Nginx adopts a phased-out resource allocation technology to occupy CPU and memory.

Low rate. Nginx officially said that it maintains 10,000 idle connections, which only occupies MB of memory. Therefore, DOS Attacks

Nginx is basically useless. For stability, nginx is better than lightHttpdBetter.
Nginx supports hot deployment. It is easy to start and can run almost without interruption.

New startup. You can also upgrade the software version without interrupting the service.
Nginx adopts the master-slave model, which can take full advantage of SMP and reduce the blocking delay of working processes on disk I/O. When

When you use select ()/poll (), you can also limit the number of connections of each process.
The Nginx code quality is very high, the code is very standard, the method is mature, and the module expansion is also very easy. It is particularly worth mentioning that

UpsTrEam and Filter chain. Upstream lays a good foundation for writing communication modules with other servers, such as reverse proxy.

. The coolest part of the Filter chain is that each filter does not have to wait until the previous filter is executed. It can output the previous filter

As the input of the Current filter, this is a bit like a Unix pipeline. This means that a module can startCompressionSent from the backend server

And the compression stream can be switched to the client before the module receives the whole request from the backend server.
Nginx adopts the latest features provided by some operating systems, suchDfIle (Linux 2.2 +), accept-filter (FreeBSD 4.1 + ),

TCP_DEFER_ACCEPT (Linux 2.4 +) support, greatly improving the performance

Ii. Install and debug Nginx
1. Install Pcre

./Configure
Make & make install
Cd../
2. nginx compilation and Installation

./Configure-user = www-group = www-prefix =/usr/local/nginx/-with-http_stub _StatUs_moDuLe

-With-openssl =/usr/local/openssl
Make & make install
For more detailed module customization and installation, refer to the official wiki.

3. Nginx configuration file test:

#/Usr/local/nginx/sbin/nginx-t // key to the Debug configuration fileCommandImportant support is required.

09:08:35 [info] 28412 #0: the configurationFile/Usr/local/nginx/conf/nginx. conf

Syntax is OK
09:08:35 [info] 28412 #0: the configuration file/usr/local/nginx/conf/nginx. conf

Was testedSuCcessfully

4. Start Nginx:

#/Usr/local/nginx/sbin/nginx
5. Modify and reload the Nginx configuration file:

#Kill-Hup'Cat/Usr/local/nginx/logs/nginx. pId
`
Iii. Nginx ReWrite

1. Nginx Rewrite basic mark (flags)
Last-this Flag is basically used.
※It is equivalent to the [L] Mark in Apache, indicating that rewrite is completed and subsequent rules are no longer matched.
Break-Abort Rewirte and stop matching
Redirect-return the HTTP status 302 of the temporary redirect
PeRmAnent-returns the HTTP status 301 for permanent redirection
※The original url supportsRegular ExpressionThe rewritten url does not support regular expressions.

2.Regular ExpressionMatch, where:
*~ Case-sensitive matching
*~ * Case-insensitive match
*!~ And !~ * Case-insensitive and case-insensitive

3. file and directory matching, where:
*-F and! -F is used to determine whether a file exists.
*-D and! -D is used to determine whether a directory exists.
*-E and! -E is used to determine whether a file or directory exists.
*-X and! -X is used to determine whether a file is executable.

3. Some available global variables of Nginx can be used for condition judgment:

$ Args
$ Content_length
$ Content_type
$ Document_root
$ Document_uri
$ Host
$ Http_user_agent
$ Http_cookie
$ Limit_rate
$ Request_body_file
$ Request_method
$ Remote_aDdR
$ Remote_port
$ Remote_user
$ Request_filename
$ Request_uri
$ Query_string
$ Scheme
$ Server_protoCol
$ Server_addr
$ Server_name
$ Server_port
$ Uri
Iv. Nginx Redirect
Redirect all linuxso.com and netseek.linuxso.com domain names to the http://www.linuxso.com

Server
{
Listen 80;
Server_name linuxso.com netseek.linuxso.com;
IndExIndex.html index.Php;
Root/data/www/wwwroot;
If ($ host !~ "^ Www.linxtone.org $ "){
Rewrite ^ (. *) http://www.linuxso.com $1 redirect;
}
........................
}
5. automatically add a slash to the Nginx directory:

If (-d $ request_filename ){
Rewrite ^/(. *) ([^/]) $ http: // $ host/$1 $2/permanent;
}
Or
Server_name_in_redirect off;
Vi. Nginx Location

1. Basic Syntax: [basically consistent with the above rewrite Regular Expression matching syntax]
Location [= | ~ | ~ * | ^ ~] /Uri /{... }
*~ Case-sensitive matching
*~ * Case-insensitive match
*!~ And !~ * Case-insensitive and case-insensitive

Example 1:
Location = /{
# Matches the query/only.
# Match/query only.
}
Match any query because all requests start. However, regular expression rules and long block rules are preferentially matched with queries.

Example 2:
Location ^ ~ /Images /{
# Matches any query beginning with/images/andHaltS searching,
# So regularExprEssions will not be checked.
# Match any queries starting with/images/and stop searching. No regular expression will be tested.

Example 3:
Location ~ *. (Gif | jpg | jpeg) $ {
# Matches any request ending in gif, jpg, or jpeg. However, all
# Requests to the/images/directory will be handled
}
# Match any request that has ended with gif, jpg, or jpeg.

Supplement:

? Ming 1: location =/uri /{...}
? Suppress loops ?? Uri ?? T. If yes, the search will be stopped? Why? /P>

? Ming 2: location ~ /Uri /{...}
? Why? ^ Shard size ?? ? Representation.

? Ming 3: location ~ */Uri /{...}
? Why? ^ Shard size ?? ? Representation.

? Ming 4: location ^ ~ /Uri /{...}
Often used? Character, regular? The regular expression is no longer used after the character.

VII. Nginx expires

1. AccordingFile TypeExpires

# Add expires header for static content
Location ~ *. (Js | css | jpg | jpeg | gif | png | swf) $ {
If (-f $ request_filename ){
Root/data/www/wwwroot/Bbs;
Expires 1d;
Break;
}
}
2. Determine a directory

# Serve static files
Location ~ ^/(Images | javascript | js | css | flash | media | static )/{
Root/data/www/wwwroot/down;
Expires 30d;
}
VIII. Nginx anti-leech Protection

1. for different file types

# Preventing hot linking of images and other file types
Location ~ * ^. +. (Gif | jpg | png | swf | flv | rar | zip) $ {
Valid_referers none blocked server_names * .linuxso.com linuxso.com http: // localhost

Baidu.com;
If ($ invalid_referer ){
Rewrite ^ /;
# Return 403;
}
}
2. for different directories

Location/img /{
Root/data/www/wwwroot/bbs/img /;
Valid_referers none blocked server_names * .linuxso.com http: // localhost baidu.com;
If ($ invalid_referer ){
Rewrite ^ /;
# Return 403;
}
}
3. The same method for implementing anti-Leech and expires

# Preventing hot linking of images and other file types
Location ~ * ^. +. (Gif | jpg | png | swf | flv | rar | zip) $ {
Valid_referers none blocked server_names * .linuxso.com linuxso.com http: // localhost;
If ($ invalid_referer ){
Rewrite ^ /;
}
Access_log off;
Root/data/www/wwwroot/bbs;
Expires 1d;
Break;
}
IX. Nginx Access Control

1. Nginx ID card verification

First, add nginx. conf
Location ~ ^/Script /{
Auth_basic "welcome to key0.cn ";
Auth_basic_user_file/var/www/test/script/. htPasswd;
}
#Mkdir/Var/www/test/script
# Perl-e &LsQuo; print (crypt (key0, cn). "n"); 'cnx9inayt9uum
# Echo 'kindle: cnx9InAYT9uuM '>/var/www/test/script/. htpasswd
#/Usr/local/nginx/sbin/nginx-s reload
2. Nginx prohibits access to a certain type of files.
For example, to prohibit access to the *. txt file under Nginx, the configuration method is as follows.

Location ~ *. (Txt | doc) $ {
If (-f $ request_filename ){
Root/data/www/wwwroot/linuxtone/test;
# Rewrite ..... Can be redirected to a URL
Break;
}
}
Method 2:

Location ~ *. (Txt | doc) $ {
Root/data/www/wwwroot/linuxtone/test;
Deny all;
}
Instance:

Prohibit Access to a directory

Location ~ ^/(WEB-INF )/{
Deny all;
}
3. Use ngx_http_access_module to restrict ip Access

Location /{
Deny 192.168.1.1;
Allow 192.168.1.0/24;
Allow 10.1.1.0/16;
Deny all;
}
See wiki: http://wiki.codemongers.com/NginxHttpAccessModule#allow

4. Nginx download limits concurrency and speed

Limit_zone linuxtone $ binary_remote_addr 10 m;
Server
{
Listen 80;
Server_name down.linuxotne.org;
Index index.html index.htm index. php;

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.