Optimization of Nginx configuration items and some parameters __nginx

Source: Internet
Author: User
Tags builtin epoll md5 encryption sendfile syslog tld
nginx configuration and partial optimization components of a configuration file:

Master profile: nginx.conf//No fragmented configuration files, so you need to add the include conf.d/*.conf for your own fragment settings
/etc/nginx/conf.d/*.conf
FastCGI profile:/etc/nginx/fastcgi.conf (new) fastcgi_params (PHP pass parameters) fastcgi _conf.default (default configuration)//use which of the best master configuration files indicated, The first two are combined with PHP
Uwsgi_params//Definition fastcgi and Pam binding
/usr/local/nginx/html//Main test page

Configuration directives (must end with semicolons):
Main BLOCK: Valid for HTTP and mail modules;
Directive value1 [value2 ...];
Support for using variables:
Built-in variables: Introduced by the module, can be directly referenced;
Custom variable: set variable_name value;
Reference variable: $variable _name

Configuration file Organizational Structure
Backup before configuration, the options in the configuration file depend on the module at installation time.

    Main block  //global configuration,
    event {...
    }   Event-driven related configuration segment;
    http {
    ...
    }  The configuration of HTTP.
    Mail {
...       
}//mail related configuration

HTTP configuration segment://below can have more than one server virtual host, or

HTTP {
...
...
server {
    ...
    server_name    //name
    root   //indicates root path
    alias  //indicates map
    location/uri/{     //indicates
    }
    ...
}
server {
...
}   One for each host, even one.
}
Main Configuration segment:

Configuration Directive Category:

Normal operation of the necessary configuration,
optimize performance-related configuration,
for debugging, positioning problem configuration;
required configuration for normal operation:User USERNAME [GroupName]; Specify the users and groups that are used to run the worker process;
User Nginx Nginx; Pid/path/to/pid_file; Specifies the PID file path for the nginx process, which can be viewed in the official document.
Pid/var/run/nginx.pid; Worker_rlimit_nofile_number #; Specifies the maximum number of file descriptors that a worker process can open; worker_rlimit_sigpending #; Specify the number of signals that each user can send to the worker process; Performance Optimization-related configuration:

Worker_processes #|auto; Indicates the number of worker processes in the worker process, which should typically be reduced by 1 for the number of physical CPU cores, since the number of CPUs starts at 0.
Can be "auto", to achieve automatic setting;

Worker_cpu_affinity Cpumask | Auto ...; Affininty Affinity
Let each kernel run a nginx process, if not such CPU rotation is the process switch out again to switch in, not necessarily the original CPU,CPU local cache can not be hit, performance is not guaranteed; this produces unnecessary waste.
Cpumask:cpu Mask below is Drop 1,2, 3 4 CPUs on
0001; 0010; 0100; 1000 indicates which CPU is running on, and the 1 masked bits are several on the first few. And then minus one. Because the number of CPUs starts from 0.
PS Axo Commond, PIB,PSR//View effect command PID which CPU
Worker_cpu_affinity 00000001 00000010 00000100; The number or CPU on which the operation is running.
Master work is very leisurely, so do not bind worker_priority nice; To adjust the worker process priority
[ -20] timer_resolution interval; The resolution of the timer, reduce this value, can reduce the number of gettimeofday () system calls debugging, positioning problem configuration: daemon off|on; Whether to start Nignx in daemon mode, when debugging should be set to off, the relevant information will be exported to the screen; master_process On|off; Whether to run Nginx with the Master/worker model, set to off when debugging;

Error_log/path/to/error_log level;
Error_log File | stderr | Syslog:server=address[,parameter=value] | memory:size [Debug | info | notice | warn | error | crit | alert | Emerg];
Error log files and their levels, which can be set to debug for debugging purposes, but debug works only when the "–with-debug" option is used at compile time;
Configuration options that can be placed in the server above.
Way:

File/path/to/some_log_file;
STDERR: Send to error output;
Syslog:server=address[,parameter=value]: Sent to the syslog server;
Memory:size log write to buffer and write to disk slowly
Log level: Debug depends on the –WITH-DEBUG option when configure; nginx.conf configuration event Related:

The main configuration segment does not need to be enclosed in parentheses
Events {
...
} worker_connections #; The maximum number of concurrent requests that each worker process can respond to, and the default 512.
Limited by Worker_rlimit_noflie (number of files that can be opened)
worker_proceses * Worker_connections = the number of concurrent connections that the current nginx can respond to use [epoll|rgsig|select|poll]; Indicates the method for processing concurrent connection requests. Linux is Epoll. Define the use of the event model; Nginx is recommended for automatic selection; Accept_mutex [On|off]; Master dispatches the load balancing lock that the worker receives the user's request; When enabled, represents a accept () system call used to enable multiple worker rotations to respond to new requests alternately and in a serialized manner. If disabled, resource competition may occur. Accept_mutex_delay time//Set the minimum latency to obtain a mutex. The default 500ms. Lock_file/path/to/lock_file; The lock file path used by the Accept_mutex. socket or host-related directives

HTTP {
...
}//Nginx uses the lock mechanism to guarantee mutual exclusion.

http{
...
}//Related configuration. server {}//define a virtual host; there is no difference based on IP and host name. Server is inside HTTP.

server {
    listen PORT; 
    server_name name;
    Root/path/to/documentroot;
    }

Attention:
(1) Monitoring on different ports based on port;listen instruction;
(2) based on hostname; The server_name instruction points to a different host name;
(3) ip-based virtual host; listen Ip:port//is rarely used. The host name of the IP and name differs little.
-Listen//

Listen address[:p ort] [default_server] [SSL] [Backlog=number] [rcvbuf=size] [sndbuf=size];
Listen port [default_server] [SSL];
Listen Unix:path [Default_server][ssl]; Third kind of socket, UNIX socket.

Default_server: Sets the default virtual host, for use on IP addresses, or for any name that does not correspond to any one server;
SSL: Used to restrict service delivery through SSL connections only;
Backlog: The length of the backup queue;
Spdy:spdy Protocol (speedy), in the case of compiling the Spdy module, is used to support the SPDY protocol;
Http2:http version 2;
SNDBUF: The size of the send buffer.
RCVBUF: Receive buffer size; server_name name [...]; Indicates the server name of the current host.
Can be followed by one or more host names, support the use of arbitrary length of any character, name can also use the wildcard wildcards expressions expression (~);

(1) first make exact match; for example: www.magedu.com
(2) left wildcard character; for example: *.magedu.com
(3) Right wildcard character, for example: www.magedu.*
(4) Regular expressions, for example: ~^.*\.magedu\.com$//~ at the beginning, if the matching to many host names, priority is 1 2 3 "4"
(5) Default_server

Tcp_nodelay On|off; Whether the connection to KeepAlive mode uses the Tcp_nodelay option (small resources are not responded to, but are returned together);

Sendfile On|off; (The kernel encapsulates the response message) whether the Sendfile function is enabled;

Tcp_nopush On|off;
Whether the Tcp_nopush (freebse) or tcp_cork (Linux) option is enabled, is useful only if sendfile is on. (); path-related directives:

NGINX-T-S
-Root sets the path mapping of the Web resource; The directory path used to indicate the document of the local file system for the URL to which the user requested;
Available Contexts: http,server,localtion,if

mkdir  -PV  /web/html           
server {
        ...
        Root  /data/www/vhost1;
    }

Http://www.magedu.com/images/logo.jpg–>/data/www/vhosts/images/logo.jpg

server {      //will require three lines to set the virtual host listen,server_name  root
        ...
    Listen;    
    server_name  www.magedu.com;
    location/images/{    
    root  /data/imgs/;
    ...
    }
  }

http://www.magedu.com/images/logo.jpg–>/data/imgs/images/logo.jpg Location [= | ~ | ~* | ^~] URI {...}////According to resource type selection corresponding , location is used to select resources.
Location @name {...}
Function: Allows the defined location (matching resource) to be matched according to the URI requested by the user, and when matched to, the request is processed by the configuration in the corresponding location block; In short, it is used to provide a specific configuration for URIs that require a dedicated configuration. A location can be nested;

server {
    ...
    server_name www.magedu.com;
    root/data/www;
    Location  /admin/  {
    configuration  A  
    }
 }  

Location patter
exact matching of =:uri;
~: Make regular expression match, distinguish character case;
~*: Make regular expression match, do not distinguish character case;
^~:uri the left half of the match, does not distinguish between character case;

Match priority: Exact match = > ^~ > ~ or ~* > unsigned URL; alias path;
It can only be used for location configuration segments, defines path aliases, and a mechanism for document mapping;

Location  /i/{
       alias   /web/html/;
        }   

Visit Http://xxxx/i/a.jpg-–>/web/html/a.jpg

      location/bbs/{
     root/web/forum/;    
    }   

The visit was/web/forum/bbs/a.jpg.

Attention:
Root instruction: The given path corresponds to the "/url/left" url;/images/test.jpg–> in location/data/imgs/images/test.jpg
Alias directive: The given path corresponds to the location "/uri/" This url;/images/test.jpg–>/data/imgs/test.jpg

Index file ...;
Effective Position: Http,server,location
The default main page, different location can be used in different home pages;

Error_page code ... [=[response]] URI;
Depending on the user's request for a resource's HTTP response status Code redirect error page, you can also redirect multiple states to a page;

    Error_page  404  /404.html    //This is a relative position
    error_page 404 =200/404.html     // Responds with the specified response status code.
Try_files file ... uri;
Try_files file ... =code;
Effective in server location
Try to find the 1th to N-1 file, the first is the resource returned to the requester; if 1 to N-1 file does not exist, jump to the most URI (must not match to the current location, but should match to the other location, otherwise it will cause a dead loop);
Cases:
location/test {
try_files test1.html  test2.html   test3.html    xxxx
}     //start matching name, The status code at this point is 404 and can be specified as a status code.
location = 50x.html {
root  html 
}  //When user exact match is only accessed HTML under root, root for installation nginx root path.
client Request-related configuration:Keepalive_timeout timeout [header_timeout];
The timeout length of keepalive connection is set, 0 indicates that long connection is forbidden, the default is 75s; keepalive_requests number;
The maximum number of resources allowed on the keepalived connection, the default is keepalive_disable none | Browser ...;
Indicates which browsers are prohibited from using the KeepAlive feature; Send_timeout #;
The timeout for sending response messages is long, and the default is 60s. In particular, the length of time between two write operations; Client_body_buffer_size size;
The buffer size used to receive the body of the client request message, which defaults to 16k, and is moved to disk when it exceeds this specified size; client_body_temp_path path [Level1 [Level2 [LEVEL3]]];
Set the temporary storage path and subdirectory structure and quantity for storing client request body, too much buffering will find difficulty, set the level;
Client_body_temp_path/var/tmp/client_body 2 2; Two 16 digits to create a level subdirectory, 2 16 to create 2-level subdirectories; client_max_body_size= #M//user upload file size (also need to change PHP.) INI parameter) configuration that restricts client requestsLimit_excpet method {...}//access control for methods other than the specified range;
Cases:
Limit_except get  {  //specified method
    allow  172.16.0.0/16;       You can use host deny all for all methods
    ;     Other hosts cannot use a method other than get
}
Limit_rate speed; Limit the number of bytes the client can transmit per second, and the default of 0 means no limit;
Cases:
Location =/index.html {
    limit_rate 2048   //unit is Bytes/second
}
file operation optimization related configurationAIO On|off | Threads[=pool]; To open the AIO function, how many threads to use, understand.
Effective in Http,server,location

Directio Size|off; Set the size of direct I/O, or turn off I/O.
Write requests are not cached and are brushed directly onto the disk. Slow, high reliability.
Enables the use of the O_direct flag (FreeBSD, Linux), the F_nocache flag (Mac OS X), or the Directio () function (Solaris) , when reading files this are larger than or equal to the specified size.

Open_file_cache off; The file cache that is open.
Open_file_cache max=n [Inactive=time];
Nginx can cache the following three types of information (file metadata):
(1) file descriptor, file size, and the most recent modification time;
(2) The structure of the Open directory;
(3) Information on files not found or not authorized to operate;

Max=n represents the maximum number of items that can be cached, and once the upper limit is reached, the least recently used cache entry is removed from the cache using the LRU algorithm;
Inactive=time: A cache entry that is not accessed in the time specified here is an inactive cache entry and is therefore deleted directly; Open_file_cache_errors [on | off]; Whether to cache file-related information when errors occur when searching; open_file_cache_min_uses #; The number of times that a cached item should be accessed at least during an inactive period before it can be called an activity item; Open_file_cache_valid #; The validity of the cached item in the cache is checked every once in a while; the default is 60s; Other Modules

Configuration of the Ngx_http_access_module module (IP-based access control)
Application Context: HTTP, server, location, limit_except

Allow Address | CIDR | UNIX: | All;
 Deny Address | CIDR | UNIX: | All;   Rule order is important.

Configuration of the Ngx_http_auth_basic_module module (Basic authentication)

Auth_basic String | Off

The user is authenticated using the HTTP Basic authentication protocol;

Auth_basic_user_file file;

The implementation of user-certified account files;
File format:

Name1:password1
name2:password2:comment  //third item can be described

Password format:

(1) Encrypted with the crypt () function; 
(2) MD5 encryption; 
(3) Htpasswd-c-m/etc/nginx/.ngxpasswd;

Cases:

location/admin/{
auth_basic "admin area";     AUTH_BASIC_USER_FILE/ETC/NGINX/.NGXHTPASSWD written directly
;
                   
ngx_http_stub_status_module Module configuration (Super Important):

Nginx the basic state information of the specified URI output. Stub status;
On the nginx1.8 version, there is no need to add on and it doesn't matter if you add it. Pre-1.8 version high needs to be added on. Indicates open.

location/admin {
stub_status on;   /No on will be an error;
}
Active connections:1  
Server accepts handled requests   //past 16630948 16630948-31070465
reading:6 
writing:179 waiting:106     //Now          

Active connections: Number of client connections currently active;
accepts: Total number of client connections accepted;
Handled: Total number of client connections already processed;
requests: Total number of requests for clients;
readking: Number of client requests being read;
writing: The number of connections to which the response message is being sent;
waiting: The number of idle connections waiting for the request to be made;

Ngx_http_referer_module module configuration (access control based on the value of the Referer header in the request message)
The Ngx_http_referer_module module is used to blocks access to a site for requests with invalid values in the Referer Der field.
-Valid_referers None | Blocked | Server_names | String ...;
To define legitimate Referer data:

None: The request message does not exist Referer header;
blocked: There is a referer header in the request message, but it has no valid value, or its value does not begin with http://or https://;
Server_ Names: Its value is a host name;
arbitrary string: A direct string, you can use the * wildcard character;
Regular expression: a regular expression starting with ~;

Built-in variables: $invalid _referer (all reference requests that do not conform to the Valid_referer specified definition are illegal references; The built-in variables cannot be matched by references)
Example:

Valid_referers   None   blocked   server_names   *.magedu.com   example.*  www.example.org/ Galleries/   ~\.google\.;   
if ($invalid _referer) {
    return  403;
    
HTTPS configuration for Nginx

Load at compile time using module Ngx_http_ssl_module

SSL On|off//whether to start SSL functionality for the current host.
ssl_certificate FILE  //Current host used certificate in PEM format.
Ssl_certficate_key File://Current host certificate private key files.
ssl_protocols[sslv2][sslv3][tlsv1][tlsv1.2][tlsv1.1];//Support encryption mode
Ssl_session_cache off |none |[ Builtin[:size]][share:name:size];      //specify session caching mechanism;
    BUILTIN: Use OpenSSL built-in mechanism, each worker is unique. Cache hits are not high. Shared
    cache that is shared by each worker, name: Cache space Names Size: The amount of cache unit space in bytes, 1M can cache 4,000 sessions;//Shared memory only, no builtitin.
ssl_ciphers  //
ssl_perfer_server_ciphers   //Preferred algorithm for using SSL server.
ssl_session_timeout time;//session timeout length. A session that refers to a cached entry in Sslsessioncache

HTTP is based on IP recognition. SSL is at the TCP layer.

Configuring certificates, keys, server name,location
nginx Access Log

Configuration of the Ngx_http_log_module module
The Ngx_http_log_module module writes request logs in the specified format.//can specify the format of the log
Access_log path [format [Buffer=size [Flush=time]] [if=condition]];
Access_log path Format gzip[=level] [buffer=size] [flush=time] [if=condition];
Access_log Syslog:server=address[,parameter=value] [format [if=condition]];
9:33
Access_log off; Access log file path, format name and cache size and brush time interval; it is recommended to define buffering to improve performance;
Log_format name string ...;
Define the log format and its name; The log format is generally defined by calling built-in variables;
Open_log_file_cache max=n [Inactive=time] [min_uses=n] [valid=time];
Open_log_file_cache Off|on; Default shutdown

Max Max cache entry;
incative=time: Inactive time long;
min_uses: Minimum usage; '
valid: An entry that verifies the validity of a cached entry.
URL rewrite for nginx

Ngx_http_rewrite_module Module Configuration
Rewrite up to 10 times to prevent a dead loop. 10:10.
Function: Dynamic resource static (some dynamic resources have not changed the application), convenient search engine reading, can facilitate caching, improve the safety and professionalism of the site.
The URL of the user request is checked based on the regex, and the match is replaced with the string specified by replacement, and the back-end server handles the converted URL Rewite
Multiple rewrite rules that exist in the same location are checked from top to bottom (loops), and flag can be used to control the secondary loop function;

If the replacement is started with a http://or https://, the result will be returned directly to the client in a redirected manner;
Match rule:
Top-down, processing article by article. Deal with it and no longer deal with it.
Rewrite the requested URL based on a regular expression;
http–> HTTPS, domain1.tld–> domain2.tld, uri1–> uri2, ...

Processing is likely to be done in a.jpg->a.html processing and then converted again to JPG to return to the user.
Instructions:

Rewrite regex replacement [flag]; 。 Speak clearly and make it clear.
Regex: A regular expression that matches the URL of a user request, such as (. *) \jpg---> $1.html can also cross hosts.
Replacement: the result of rewriting;
[flag]: Control the work process. Originally made the first inspection after the direct humanitarian back end, now to do multiple processing. The following keyword is added directly behind the keyword.

    stop further processing of the current URI after the last//rewrite, and match the new round of processing of the new URL (again) similar to conntine; Stop the
processing of the URI after the break    //rewrite is completed, and turn to the other configuration behind it; The overridden rule C end is not visible.
redirect    //rewrite will return a temporary redirect to the client after the client has a new URL to request (Temporary 302)//the client is visible; (just return a URL at the time of the matching rule (at which point the backend is not processed). The browser automatically accesses the server with the new URL.
after the permanent    //rewrite is completed, a permanent redirect is returned to the client (the overridden URL, which the client will initiate the request to), and the client initiates a request for the new URL (permanent 301);

For example:

server{
  Location  /{
    root mp3;
    Index xxxxx
    rewite ^/(download/.*)/media/(. *) \.*$/mp3/$2.mp3 last;  Access media under MP3
, directed to MP3 under MP3
    }
}
Pcre Regular expression meta character
character matching:., [], [^]
times Match: *, +,?, {m}, {m,}, {m,n}
position anchor: ^, $
or: |
Group: (), back to quote, $, $, ...

Regwrite_log on | Off//Whether to enable the rewrite log, by default. When enabled, log information is sent to the error log;
Debug method: Error log debug; open rewrite_log;

if (condition) {...}://Conditional judgment executes the configuration when the condition is met, referencing the new configuration context;
The internal variables are usually judged.
Condition comparison expression:

==,!=
~: pattern matching, distinguishing character case;
~*: pattern matching, case-insensitive;
!~: pattern mismatch, character case sensitive,
!~*: pattern mismatch, case-insensitive;

Document and directory existence judgment:

-F,!-f: exists and is a normal file;-
D,!-d: exists and is a directory;-
E,!-e: exists;
x,!-x: exists and is executable;

/Watch the video screen 11:09
Return

return code [text];  
return code URL;
return URL;
Immediately stops processing the requested URI and returns the specified status code;

There are many variables in the nginx.org/en/docs/http/ngx_croe_module.html.
Set $variable value; Custom variable assignment, the variable in the assignment and reference need to add ' $ ';
Examples of if:

if ($httpd _user_agent ~ Msiie) {
  rewrite ^ (. *) $/msie/$1 break;    Add a resource regardless of what is requested;
}
if ($http _cookie ~* "id=" ([^;] +) (?:; |$ ") {
  set $id $    
}  The value of the cookie in the header of the request message, setting a variable ID with a value of $;
if ($request _method =post) {return
405;//Deny 405
}
if ($slow) {
    limit_rate 10k;//Slow user is divided to 10k rate;
}
if ($invalid _referer) {return
    403;  Blacklist 403, return;
}

REDIRECT 80 to 443 ports:

server{
Listen;
server_name www.abc.com
Rewrite ^ (. *) https://$server _name$1  permanent;   Overrides after matching to any rule and emits a permanent permanent redirect.
}
server{
    listen 443;
    server_name www.abc.com;
    root  /path/to/root;
    SSL on;
    SSL_CERTIFICATE/ETC/NGINX/CERTS/SERVER.CRT;
    Ssl_certificate_key/etc/nginx/certs/serer.key;
}
nginx Compression Transfer

Ngx_http_gzip_module Module Configuration--is a filter that compresses the specified content. Not all browsers will support
gzip on | Off Enable or disable the Gzip compression response message;
Gzip_comp_level level; Compression ratio, 1-9, default is 1;
Gzip_disable regex ...; A regex is a regular expression used to match a client browser, indicating that no compression response is performed on all matching browsers;
Gzip_min_length length; The minimum length of the response message that triggers the compression function;
Gzip_http_version 1.0 | 1.1; Set the minimum version of the Protocol when the compression function is enabled;
Gzip_types Mime-type ...; Indicates which types of resources perform compression operations only; the default is text/html;
Gzip_proxied off | Expired | No-cache | No-store | Private | no_last_modified | No_etag | Auth | Any ...; Defines the ability to enable compression on a resource that is requested by the client with which request property, such as expired, which enables compression for objects that cannot be cached because of the use of the expire header; talk about caching.
Example:

gzip on  ;
Gzip_http_version 1.0;
Gzip_comp_level 6;
Gzip_disable msie6;
Gzip_min_length 2;  How much to compress
gzip_types text/plain text/css text/xml application/x-javascript application/xml Application/java-script;  These are all static resources
server {
       rewrite ^ (/download/.*)/media/(. *) \. *$ $1/mp3/$2.mp3 last;
    Rewrite ^ (/download/.*)/audio/(. *) \. *$ $1/mp3/$2.ra last  ;  
   return  403;
   ...
    }               

Http://www.magedu.com/download/a/b/c/media/32.wmv-->/download/a/b/c/mp3/32.mp3

Location/{
    root html;
    Index index.html index.htm
    rewtrite (. *) \.txt$$1.html
}

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.