The nginx configuration file to learn

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

The nginx configuration file is divided into six areas:

main section, events section, http section, sever section, location section, upstream section.

main module:

The main control process of the user / user group, school children file descriptors process number, the error log position / level, PID location, sub process priority, process corresponding to CPU, the process to open.

user kingnet kingnet;
worker_processes 4;
error_log logs/error.log notice;
pid logs/nginx.pid;
# worker_priority -5;
# worker_cpu_affinity 0001 0010 0100 1000;
worker_rlimit_nofile 1024;
Note: the worker_cpu_affinity: specified process corresponding to the CPU, the above configuration is the first process corresponding to cpu0, second processes corresponding to CPU1, third processes corresponding to CPU2, fourth a process corresponding to the cpu3, you can also specify a process corresponding to a plurality of cpu. For example, 0101 indicates a process corresponding to cpu0/cpu2.
Worker_rlimit_nofile: specifies the number of file descriptors for each woker can open, general and worker_connections value are the same.

event module: Control nginx connection mode.

1234 events {
use epoll;
worker_connections 1024;
}
Note: use: using a network IO model, epoll model is much higher than the efficiency of select model.
worker_connections: Each worker can handle the maximum number of connections, depending on the ulimit -nvalue.
Nginx number of concurrent connections: <worker_processes*worker_connections.
HTTP Access module provides a host name access control based on the simple. Through this module, you can allow or the specified IP address or IP address segment access to certain virtual host or prohibited category
The allow instruction
Grammar: allow [address|CIDR|all]
The use of the environment: http, server, location
Effect: allows you to specify the IP address or IP address to access some virtual host or directory
The deny instruction
Grammar: deny [address|CIDR|all]
The use of the environment: http, server, location
Effect: or directory from the specified IP address or IP access to certain virtual host
Matching rules
Control rules are examined in the order of declaration, the first matching access rules of IP will be used
Demonstration cases
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
deny all;
}
Interpretation:
Prohibition of 1 192.168.1.1 the IP address access
192.168.1.0/24 2 allows the address of IP access, but since 192.168.1.1 first matching of deny, so 192.168.1.1 is not accessible
3 when the IP address does not match the 1,2 two rules, will be banned from all IP addresses
HTTP core is mainly used to control the request processing client.
The main parameters:
sendfile on;Use the file descriptor copy data, done in the kernel state
tcp_nopush on;Effective in sendfile open
keepalive_timeout 60; Long connection (a connection can continuously send multiple packets) timeout
tcp_nodelay on;Effective in keepalive open
client_body_buffer_size 128k; Specifies the connection request entity buffer size
client_max_body_size 100m; Specifies the maximum size of the connection request entity
client_header_buffer_size 64k; The specified connection request entity header buffer size
large_client_header_buffers 4 64k; The specified number, use the client buffer head relatively large size
server_tokens off; Close the nginx version information
server_names_hash_max_size 1024; The maximum name hash tablevalue

Server_names_hash_bucket_size 256 name hash table and the size of each page

Note: the large size according to the /sys/devices/system/cpu/cpu0/cache/index1/size to determine the hash table, the general is a multiple of the relationship.

The server_name parameter: the host header and the parameter value HTTP request; matching
Domain names follow the priority rules:
Complete name matching
The name begins with a file wildcards: *.example.com
At the end of a file name wildcard: www.example.*
The name of a regular expression is used.
If there is no match, the following priority
The listen instruction is marked as server field default
The first listen server field.
The error_page parameter: Specifies the corresponding error page for the error code
error_page 401 402 403 404 /40x.html;
If 401, 402, 403, 404 errors are redirected to the /40x.html page, the page position requires a combination of matching rules.
Generally define a separate matching rules for the error page, for example
location =/40x.html {
root html; #To this HTML directory for this page
}

The location parameter: according to the URI matching.

Rule of grammar: location [=|~|~*|^~] /uri/ { … }
= At the beginning of that exact matching
^~ Beginning with a conventional URI beginning of the string, understood as the matching URL path. Nginx URL do not code, therefore the request is /static/20%/aa, can be matched to the rules /static//aa ^ ~ (note is empty).
~ At the beginning of that distinguish regular case matching
~* At the beginning of that does not distinguish between regular case matching
!~And! ~ * are case sensitive and case insensitive does not match the regular mismatch
/ General matching, any requests are matched to the.
Multiple location configuration in the case of matching order for (reference to, not the actual verification, try to know, do not need to worry about, for reference only):
The first match =, then the matching ^ ~, followed by regular file sequence matching, finally give / general matching. When successful matching time, stop the match, according to the current matching rule processing request.
For example, the following match rules:
location = / {
#Rule A
}
location = /login {
#Rule B
}
location ^~ /static/ {
#Rule C
}
location ~ \.(gif|jpg|png|js|css)$ {
#Rule D
}
location ~* \.png$ {
#Rule E
}
location !~ \.xhtml$ {
#Rule F
}
location !~* \.xhtml$ {
#Rule G
}
location / {
#Rule H
}
So the effect of the following:
Root access /, such as matching rules A
Access to the matching rule B, matching rule H
Access will match the rules of C
Access, the matching rules D and E, but the D order of priority rules, rule E does not play a role, but the priority is matched to the rules of C
Access is matching rule E, but not D E matching rules, because the rules are not case sensitive.
Access will not match the rules F and G, G does not match rule, because insensitive. Rule F, rule G belong to the elimination, in line with the matching rules but not to match, so think of practical applications where used.
Access is the final match to the rules of H, because it does not match the rules above, this time should be nginx forwarding requests to the backend application servers, such as FastCGI (PHP), Tomcat (JSP), nginx as the direction of the proxy server exists.

So in actual use, personally feel that there are at least three matching rule definition, as follows:
#The direct matching site root, the domain name to visit the website home page is more frequent, this will accelerate the process, official says.
#Here is directly transmitted to the back-end application server, but also can be a static page
# The first mandatory rules
location = / {
proxy_pass
}
# Second mandatory rules are static file request, this is the nginx as the HTTP server
# There are two kinds of configuration mode, matching directory matching or suffix, choose one or with the use of
location ^~ /static/ {
root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
root /webroot/res/;
}
#The third rule is the general rule, used to forward requests to a back-end application server
#Non static file request default is dynamic request, according to the actual grasp yourself
#After all, some of the current framework of popular, with.Php,.Jsp suffix is rare
location / {
proxy_pass
}

In the nginx proxy_pass configuration, if ^ ~ matching path in accordance with proxy_pass, should pay attention to the URL final /, when coupled with the /, equivalent to the absolute root path, nginx will not take part in the match the path location; if not, you will put the matching path parts are also give the agent walks.

location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass ;
}
If the above configuration, if the requested URL is http://servername/static_js/test.html
Will be acting as the
If such a configuration
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass ;
}
It will be an agent to
Of course, we can realize / using the following rewrite function
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
rewrite /static_js/(.+)$ /$1 break;
proxy_pass ;
}

Some of the available global variables:

$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

For example:

$host: localhost
$server_port: 88
$request_uri:
$document_uri: /test1/test2/test.php
$document_root: D:\nginx/html
$request_filename: D:\nginx/html/test1/test2/test.php

ReWrite grammar

The nginx type is rewrite: rewrite regex replacement flag
Rewrite can be placed in the server, location and if module.

Nginx rewrite instruction execution sequence:

1 server blocks the execution of rewrite instructions (here refers to the block after the keyword server {} region surrounded by the other, XX blocklike)
2 implementation of location matching
3 selected location rewrite instruction
If one step URI is overridden, then re executes 1-3, until you find the real file
If the circulation of more than 10 times, or 500 Internal Server Error error

The four flag marker type:
last – The equivalent of Apache L
break – Suspend Rewirte, not to continue the match
redirect – Returns a temporary redirect HTTP status 302, equivalent to Apache in R
permanent – Returns a permanent redirect HTTP status 301, equivalent to Apache in R=301

1, The following is the expression can be used to judge:
-f and -f are used to determine whether a file exists
-d and -d are used to determine whether there is a directory
-e and -e are used to determine whether there! A file or directory
-x and -x are used to determine whether a document! Executable

The allocation of nginx upstream currently supports 4 modes

1), Polling (default)
Each request according to the time sequence are assigned to different backend server, if the server down off, can automatically remove.
2), weight
Specify the polling probability, weight and access rate is proportional to the back-end server performance, uneven, the default is 1.
2), ip_hash
Each request to access the IP hash results distribution, so that each visitor fixed access a back-end server, session can solve the problem of.
3), Fair (third party)
According to the response time of the back-end server to assign priority allocation request, response time is short.

4), Url_hash (third): according to the URL hash results to the allocation request, so that each URL directed to the same backend server

Add the HTTP node:
#The definition of load balancing device of Ip and equipment state
upstream myServer {
server 127.0.0.1:9090 down;
server 127.0.0.1:8080 weight=2;
server 127.0.0.1:6060;
server 127.0.0.1:7070 backup;
}
#Add in the Server node using the load under
proxy_pass http://myServer;
#A server can be configured with multiple equilibria, air spaced

The upstream status of each device:
Down represents a single server before temporarily not participating in the load
Weight default is 1.weight larger load, the more weight.
max_fails : Number of allowed requests failed 1 by default when more than the maximum number, return to the proxy_next_upstream module defined error
Fail_timeout:max_fails failed, pause time.
backup: All other non backup machine down or busy time, request the backup machine. So this machine will be the lightest pressure.
Nginx also supports load balancing of multi group, you can configure multiple upstream services in different Server
Configure load balancing is relatively simple, the question is how to realize the sharing but between session servers
There are many ways (the following content from the Internet, fourth methods are not practical.)
1) Do not use session, for cookie
If the program logic is not complex, the session into cookie
2) The application server to realize the sharing of
Can use a database or memcached to save session, its efficiency is not high, not suitable for the requirements for high efficiency.
3) ip_hash
Nginx ip_hash technology can be a IP requests to the same back-end, so the IP a client and a back-end can build a solid session, ip_hash is defined in the upstream configuration:
upstream backend {
server 127.0.0.1:8080 ;
server 127.0.0.1:9090 ;
ip_hash;
}
Ip_hash is easy to understand, but can only use the IP factor to assign back, so the ip_hash is defective, cannot be used in some cases:
1, Nginx is not the most front-end server. Ip_hash nginx is the most front-end server, or nginx not correct according to the IP IP, not hash. For example, using squid for the front, then nginx and IP will get a server IP address squid, the address as shunt is sure.
2, Load balancing nginx backend and other means. If the nginx backend and other load balancing, the request and through other means billabong, then the request cannot locate a client to a session application server. In that case, nginx is only pointing directly to the application server, or by a squid, and then point to the application server. The best way is to use location as a diversion, will need to be part of the session request through the ip_hash shunt, the rest go back to the other.

client_max_body_size 300m; //The number of single file byte maximum allowed the client request

client_body_buffer_size 128k; //Cache proxy client file bytes
client_body_temp_path /dev/shm/client_body_temp; //Request to write to the cache file directory path
proxy_connect_timeout600; //And the back-end server connection timeout,
proxy_read_timeout 600; //A successful connection for back-end corresponding time, the default is 60S
proxy_send_timeout 600; //Reverberation time back-end servers, provision server in a certain period of time after transmitting.
proxy_buffer_size 16k; //The proxy server cache file head file size, the default is 4K
proxy_buffers 4 32k; //The back-end is really the number and size of server
proxy_busy_buffers_size 64k; //When the system is busy, for larger proxy_buffer
proxy_temp_file_write_size 64k; //Write to the temporary directory file size
proxy_temp_path /dev/shm/proxy_temp; //The request specifies a directory to the cache is large

proxy_pass http://cluster/; //Need to specify the proxy URL,
proxy_redirect off; //If you need to open the location and Refresh fields from the rear, can open. That is to say the back-end and the proxy server, need to open
proxy_set_header X-Real-IP $remote_addr; //Permits will be sent to the backend server requests a re definition or add a field, this can be a variable is text combination.
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //Written in PS with the following, $http_x_Forwarded_for this even add in back-end Web, There was no user IP, So in the nginxThe reverse proxy to addHeaderHeader information X-Forwarded-ForIn conjunction with the back-end server log file$http_x_Forwarded_forThis can get the userIPAddress.
proxy_set_header Host $host; //The first proxy_set_header directives Header header information specified in the request to the reverse proxy server back-end Web, The back-end web server has multiple virtual host domain name based, The head information of Host, Used to specify a name for, So the back-end web can identify the reverse proxy request which virtual host processing.
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503
http_504 http_404; Various state server timeout corresponding head

Example:

upstream cluster {
server 192.168.100.238:80 weight=8 max_fails=2 fail_timeout=30s;
server 192.168.100.248:80 weight=8 max_fails=2 fail_timeout=30s;
}

server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
...

Nginx fastcgi and gzip module
The fastcgi module: nginx collaborative fastcgi
fastcgi_connect_timeout 200;
fastcgi_send_timeout 200;
fastcgi_read_timeout 200;
fastcgi_buffer_size 4k;
fastcgi_buffers 16 4k;
fastcgi_busy_buffers_size 8k;
fastcgi_max_temp_file_size 16k;
fastcgi_intercept_errors on; PHP error is returned to the nginx
Description: timeout time can be set larger, buffer size can also be provided in some.
The gzip module: data compression and transmission
gzip on;
gzip_min_length 1k;
gzip_buffers 8 8k;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;

gzip_vary on;



The rewirite instance:

Because the rewrite execution efficiency is low, usually is replaced by a return statement, such as:

rewrite (.*) $1;

Instead of

retrun 301 https://www.example.org$request_uri;


Redirect grammar

server {
listen 80;
server_name start.igrow.cn;
index index.html index.php;
root html;
if ($http_host !~ "^star\.igrow\.cn$&quot {
rewrite ^(.*) redirect;
}
}
The chain
location ~* \.(gif|jpg|swf)$ {
valid_referers none blocked start.igrow.cn sta.igrow.cn;
if ($invalid_referer) {
rewrite ^/ ;
}
}
According to the type of file set expiration time
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
expires 1h;
break;
}
}
Prohibit access to a directory
location ~* \.(txt|doc)${
root /data/www/wwwroot/linuxtone/test;
deny all;
}

Multi directory 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;
}
Directory on the
/123456/xxxx -> /xxxx?id=123456
rewrite ^/(\d+)/(.+)//$2?id=$1 last;
For example, the following set nginx in the user with IE redirects to the /nginx-ie directory:
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /nginx-ie/$1 break;
}
Directory is automatically added"/"
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
Disable htaccess
location ~/\.ht {
deny all;
}
Multiple directory prohibited
location ~ ^/(cron|templates)/ {
deny all;
break;
}
Prohibited to /data at the beginning of the file
You can disable /data/ under multi-level directory.Log.txt request;
location ~ ^/data {
deny all;
}
No single directory
Cannot disable.Log.txt can request
location /searchword/cron/ {
deny all;
}
No single file
location ~ /data/sql/data.sql {
deny all;
}
Set an expiration time for favicon.ico and robots.txt;
Here is favicon.ico for 99 days, robots.txt for 7 days did not record 404 error log
location ~(favicon.ico) {
log_not_found off;
expires 99d;
break;
}
location ~(robots.txt) {
log_not_found off;
expires 7d;
break;
}
To set the expiration time of a file; here is 600 seconds, do not record access log
location ^~ /html/scripts/loadhead_1.js {
access_log off;
root /opt/lampp/htdocs/web;
expires 600;
break;
}
File anti Daolian and set the expiration time
Here the return 412 as a custom HTTP status code, the default is 403, convenient to find the correct link request
"rewrite ^/ ;"Display a security chain
"access_log off;"Do not record access log, ease the pressure
"expires 3d"All file 3 days the browser cache
location ~* ^.+\.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;
if ($invalid_referer) {
rewrite ^/ ;
return 412;
break;
}
access_log off;
root /opt/lampp/htdocs/web;
expires 3d;
break;
}
Only with a fixed IP access to the web site, and add a password
root /opt/htdocs/www;
allow 208.97.167.194;
allow 222.33.1.2;
allow 231.152.49.4;
deny all;
auth_basic "C1G_ADMIN";
auth_basic_user_file htpasswd;
The multi-level directory files into one file, the enhanced SEO effect
/Job-123-456-789.html points to/job/123/456/789.html
rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;
The root directory of a folder to 2 directory
As /shanghaijob/ points /area/shanghai/
If you change last to permanent, then the browser address bar is significant/location/shanghai/
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
The above example has a problem is access to /shanghai will not match
rewrite ^/([0-9a-z]+)job$ /area/$1/ last;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
This /shanghai can be visited, but the relative links page cannot be used,
Such as./list_1.html address is /area/shanghia/list_1.html will become /list_1.html, leading to cannot access.
Then I add automatically jump is not
(-d $request_filename)It is a condition which is required for the real catalogue, and my rewrite is not, so there is no effect
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
Know the right reason, let me hand jump
rewrite ^/([0-9a-z]+)job$ /$1job/ permanent;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
When the file and directory does not exist redirection:
if (!-e $request_filename) {
proxy_pass ;
}
Domain jump
server
{
listen 80;
server_name jump.c1gstudio.com;
index index.html index.htm index.php;
root /opt/lampp/htdocs/www;
rewrite ^/ ;
access_log off;
}
Multi domain steering
server_name www.c1gstudio.com www.c1gstudio.net;
index index.html index.htm index.php;
root /opt/lampp/htdocs;
if ($host ~ "c1gstudio\.net") {
rewrite ^(.*) $1 permanent;
}
The three level domain jump
if ($http_host ~* "^(.*)\.i\.c1gstudio\.com$") {
rewrite ^(.*) $1;
break;
}
Domain name mirror
server
{
listen 80;
server_name mirror.c1gstudio.com;
index index.html index.htm index.php;
root /opt/lampp/htdocs/www;
rewrite ^/(.*) $1 last;
access_log off;
}
A subdirectory as mirror
location ^~ /zhaopinhui {
rewrite ^.+ last;
break;
}


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Alina at January 12, 2014 - 7:15 PM