One. Nginx configuration file
Nginx configuration file:/etc/nginx/nginx.conf/etc/nginx/conf.d/ /etc/nginx/default.d/
Configuration file Structure
The structure of the Nginx configuration file:
Main (Global configuration segment)
Events {...}
HTTP {
...
server {
Location ... {...}
Location ... {...}
...
}
server {
...
}
}
2, the configuration parameters need to end with a semicolon, syntax format:
Parameter name value 1 [value 2 ...];
3. Variables can also be used in configuration files:
Module built-in variables
User-defined variables: Set var_name value
4. configuration file Check: nginx-t
5. Overloaded configuration file: Nginx-s Reload
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Second, Nginx basic Core configuration (main segment, events{} segment)
1, the normal operation of the necessary configuration:
①user username [groupname]; #指定运行worker进程的用户和组
②pid/path/to/pidfile_name; #指定nginx的pid文件
③worker_rlimit_nofile NUM;
The maximum number of file handles that the worker process can open. The value cannot be less than worker_connectionsxworker_processes, and if Nginx works as a reverse proxy server, the value cannot be less than worker_connectionsxworker_processesx 2, because at this point a request needs to maintain two socket files.
④worker_rlimit_sigpending NUM; Set the number of signals each user can send to the worker process;
2, optimize the performance-related configuration:
①worker_processes num; The number of worker processes, usually the number should be minus 1 of the core of the CPU; auto is the default, the system automatically recognizes the setting
②worker_cpu_affinity cpumask ...; Used to define the worker process and which CPU has affinity, the worker process runs only on the specified CPU. The CPU uses the CPU mask to specify 2. You can also include "Auto" in front of the CPU mask to automatically set the affinity in the specified CPU
For example:
Worker_processes 4;
Worker_cpu_affinity 0001 0010 0100 1000;
Represents the binding of 4 worker processes on CPU0,CPU1,CPU3 CPU4
③ssl_engine device; #在存在ssl硬件加速器的服务器上, specify the SSL hardware acceleration device used;
④timer_resolution T; #每次内核事件调用返回时, the Nginx cache clock is updated with Gettimeofday (), and timer_resolution is used to define how often the cache clock is updated by Gettimeofday (); x86-64 system, Gettimeofday () The cost is already very small, can ignore this configuration;
⑤worker_priority Nice; Set the nice value of the worker process to adjust its priority to the default value of 0. The parameter range of this directive is the Nice value range (-20 to 19)
Events section
Default configuration:
Events {
Worker_connections 1024; # define the maximum number of concurrent connections per worker process
}
①accept_mutex [On|off] #是否打开nginx的负载均衡锁; This lock enables multiple worker processes to be connected to new clients in a rotating, serialized manner, typically when a worker process has a load of up to 7 per cent of its upper limit 8,master, as far as possible, no longer dispatch this worker to the request;
②lock_file/path/to/lock_file; If more than one worker process is load balanced, you need to lock the file. This option specifies the path to the lock file. You can also specify by using the./configure option when compiling the installation.
③accept_mutex_delay #ms; #accept锁模式中, the wait time for a worker process to get the accept lock, or, if a worker process fails at one attempt to acquire a lock, at least wait for #ms to request the lock again;
④multi_accept On|off; #是否允许一次性地响应多个用户请求; default is off;
⑤use [Epoll|rtsig|select|poll]; #定义使用的事件模型, it is recommended to let nginx automatically select;
⑥worker_connections #; #每个worker进程能够并发响应的最大请求数;
4, for debugging, positioning problems: Only use when debugging Nginx
①daemon On|off; #是否让ningx运行于后台; The default is on, which can be set to off when debugging, so that all information is output directly to the console;
②master_process On|off #是否以master/worker mode operation Nginx, default is on, debugging can be set off to facilitate tracking;
③error_log/path/to/error_log level; #错误日志文件及其级别; The default is the error level; Debug can be used when debugging, but requires the debug feature to be enabled at compile time using--with-debug;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ web服务相关配置
HTTP segments are used to define nginx as a Web service configuration.
HTTP segment Structure:
http{
......
server{ 【server1配置】}server{ 【server2配置】}……
}
Server is equivalent to a virtual host in httpd. The difference is that Nginx does not have a central host, and even if there is only one site, a server segment definition is used.
A configuration defined outside the server segment that takes effect for all servers. The configuration or public configuration of a non-virtual host needs to be defined outside of the server, within HTTP.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Virtual host-related configuration
⑴server {...}
Define a virtual host; Nginx supports the use of host names or IP-based virtual hosts;
Listen IP [:P ort] [OPTIONS]; Specify the address and port of the listener
root directory path; Specifies the page file root directory, if relative paths are used, relative to the compiled installation directory (the path specified at compile-time –prefix). Similar to the documentroot in httpd, but different, root is often used in the location section. After you define root, the relative path specified by each instruction is relative to root.
SERVER_NAME: Specifies the virtual host name. Equivalent to ServerName in the httpd virtual host segment, can be followed by multiple host names, the name can use the wildcard wildcards regular expression (usually beginning with a ~), when Nginx receives a request, it will take out the value of its header server, and then compare with the audience server_name ; comparison mode
① do exact matches first, such as wwb1.lishuai.com
② to the left wildcard character, as. lishuai.com
③ wildcard matches on the right, such as www.
④ regular expression matches, such as ~^.. lishuai.com$
If the host name that the client has typed in the browser can be matched to more than one of the above-mentioned ways, the priority is: exact hostname –> on the left side using –> –> regular expression matching using a wildcard
——————————————————————————————————————————————————————
Location [= | ~ | ~| ^~] Uri {...} #location只能放在server和location中, location can appear multiple times
Location @name {...}
Function: Allows to match the specified location for access configuration based on the URI requested by the user, which is processed by the configuration in the location block.
Scope of Use: Server segment, location segment
The way to match URIs, in order of precedence:
=path Exact Match path
^~path using regular expressions to match the first half of a URI
~path using regular expressions to match URIs, case-sensitive
~*path using regular expressions to match URIs, case-insensitive
Path matches directly with path, representing resources under path path
That is, priority is to match a small range before matching a large range.
Examples of official documents:
Location =/{# Only when URI is '/', use a configuration
[Configuration A]
}
When the location/{# URI is the path contained under '/', use B configuration
[Configuration B]
}
location/documents/{# URI is a path contained under '/documents/', use C configuration
[Configuration C]
}
Location ^~/images/{# URI is "/images/" in the previous section, using the D configuration
[Configuration D]
}
Location ~*. (Gif|jpg|jpeg) $ {# URI end is GIF, JPG, or JPEG, use E to configure
[Configuration E]
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++====++++
Alias defines the path alias
The command alias, which can be defined only in the location segment, defines the URI for the location specified by the location.
Like what:
location/test/{
alias/lishuai/txt/;
}
Replaces test in URI with/lishuai/txt/
For example, we were supposed to visit http://192.168.2.18/test/index.html and be replaced with http://192.168.2.18/lishuai/txt/index.html now.
Distinguish between root path and alias path:
①location/i/{
Root/data/images;
}
"/i/top.gif" will be responded to by the/data/images/i/top.gif file
②location/i/{
alias/data/images/;
}
"/i/top.gif" will be responded to by the/data/images/top.gif file
Index Definition Home Page
The instruction index is from module Ngx_\http_index_module. Used to define the home page.
Usage Range: HTTP segment, server segment, location segment. Definitions have different effective scopes in different segments. The default value is Index.html
Error_page Define error page
Directive Error_page, for customizing error pages.
Use format: Error_page code ... [=[response]] URI. Indicates that the page specified by the client URI is returned according to the Response Code code (which can be specified more than one).
Use Range: HTTP segment, server segment, location segment, if statement in location segment
The essence of Error_page is to redirect the error request for the specified URI to a custom page. The equivalent of the client re-accessing the server (just equivalent. In fact this process client does not participate, automatically by Nginx), except that the requested resource is redirected in order to customize the error page.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Network connection-related settings:
⑴keepalive_timeout time; #保持连接的超时时长; default is 75 seconds
⑵keepalive_requests N; #在一次长连接上允许承载的最大请求数
⑶keepalive_disable [msie6 | safari | none]; # Disables the use of long connections
⑷tcp_nodelay On|off for specified browsers; #对keepalive连接是否使用TCP_NODELAY选项
⑸client_header_timeout time; The timeout for reading the HTTP request header is
⑹client_body_timeout time; #读取http请求包体的超时时长
⑺send_timeout times; #发送响应的超时时长
* * Restrictions on client requests: * * 1, limit_except METHOD {...} Specifies access control for methods other than the range; limit_except GET {allow 192.168.2.0/24; Deny all; } 2, client_body_max_size size; Limiting the upper limit of the body part of the request packet, judging by the "Content_length" in the header of the request packet; 3, limit_rate speed; Limit the number of bytes that the client transmits per second, by default 0, which means no limit; 4, limit_rate_after time; When Nginx sends a response message to the client, if the duration exceeds the length specified here, then the subsequent sending process starts the speed limit; * * File operation optimization: **⑴sendfile On|off; #是否启用sendfile功能; ⑵aio On|off; #是否启用aio功能; ⑶open_file_cache max=n [Inactive=time]|off; #是否打开文件缓存功能 Max: The maximum value of the cache entry; inactive: When a cache entry is not accessed for a specified length of time, it is automatically deleted; The default is 60s cache information including: file handle, text The size of the item and the last modification time; The directory structure that has been opened; information not found or not accessible; ⑷open_file_cache_errors On|off; #是否缓存文件找不到或没有权限访问等相关信息; ⑸open_file_cache_valid time; #多长时间检查一次缓存中的条目是否超出非活动时长, the default is 60s⑹open_file_cache_min_use #; #在inactive指定的时长内被访问超此处指定的次数地, it will not be deleted;
Special handling of client requests :
⑴ignore_invalid_headers on|off;
Whether to ignore the illegal HTTP header; The default is On,off means that the first non-compliant header in the request header will reject the response; only for server and HTTP
⑵log_not_found On|off; #是否将文件找不到的信息也记录进错误日志中;
⑶resolver address; #指定nginx使用的dns服务器地址;
⑷resover_timeout time; #指定DNS解析超时时长, default is 30s;
⑸server_tokens On|off ; #是否在错误页面中显示nginx的版本号;
memory and disk resource allocation:
⑴client_body_in_file_only On|clean|off;
Whether the packet of HTTP is stored in a disk file, or not off means storage, even if the size of the package is 0, a disk file is created, and on indicates that the package body file is not deleted after the request ends, and the clean expression is deleted;
⑵client_body_in_single_buffer On|off;
The packet of HTTP is stored in buffer, default is off;
⑶cleint_body_buffer_size size;
Nginx receives the memory buffer size of the HTTP packet, and if the package exceeds this value, it is written to the disk file
⑷client_body_temp_path dir-path [Level1 [Level2 [Level3]];
A temporary directory where the HTTP package is stored;
For example: CLIENT_BODY_TEMP_PATH/VAR/TMP/CLIENT/1 2;
The number that follows represents the number of digits in the 16 system; This statement represents the creation of 16 first-level subdirectories under the/var/tmp/client directory, and then the creation of a 16*16 two-level subdirectory under each sub-directory
⑸client_header_buffer_size size;
The buffer size allocated when receiving the header portion of the HTTP packet requested by the user under normal circumstances; The default is 1k
⑹large_client_header_buffers number size;
size and number of memory buffer for storing oversize HTTP request headers;
⑺connection_pool_size size;
Nginx allocates a memory pool for each successful TCP connection, which is used to set the initial size of this memory pool, and the default is
⑻request_pool_size size;
Nginx allocates a pool of memory for each HTTP request, which is used to set the initial size of this memory pool; default is 4k
Built-in variables for HTTP core modules:
$uri: The URI of the current request, without parameters;
$request _uri: URI of the request, with full parameters;
$host: The host header in the HTTP request message, or the hostname of the virtual host that handles the request if there is no host header in the request;
$hostname: The host name of the host on which the Nginx service is running;
$remote _addr: Client IP
$remote _port: Client port
$remote _user: User name entered by client user when authenticating with user;
$request _filename: The URI of the user request is mapped by local root or alias after the local file path;
$request _method: Request method
$server _addr: Server address
$server _name: Server name
$server _port: Server port
$server _protocol: The protocol that the server sends a response to the client, such as http/1.1, http/1.0
$scheme: Use scheme in the request, such as HTTPS in https://www.lishuai.com/;
$http _header: Matches the header specified in the request packet, $http the host header in the _host matching request message
$sent _http_header: Matches the header specified in the response message, such as the Content-type header in the $http_content_type matching response message;
$document _root: The root configuration to which the current request is mapped;
Nginx as another function of Web server
1. Access Control (Http_access_module)
Allow Address | CIDR | UNIX: | All
Deny Address | CIDR | UNIX: | All
The default is allow all
Example:
Location/{
Deny 192.168.2.29;
Allow 192.168.2.0/24;
}
We allow all hosts in the 192.168.2.0 network segment to access, denying 192.168.29 this host access
2. user authentication (http_auth_basic_module)
Auth_basic String | Off
Auth_basic_user_file file;
Example:
3, when there is no default home page display file list, often used to set up a download site (http_autoindex_module)
AutoIndex on | Off
Anti-theft chain
Directive valid_referers, from module Ngx_http_referer_module. The
is used to specify which values of the Referer header in the request message are legitimate. In combination with the built-in variable invalid_referer, the request to jump from an illegal address is rejected.
Use scopes: Server segment, location segment
⑴ Define a reference to a compliance
Valid_referers None | blocked | server_names | string ...;
Description:
None: "Referer" request header is missing,
blocked: "Referer" request header exists, but its value is deleted by firewall or proxy server; string as the beginning;
Server_names: "Referer" The request header contains a virtual hostname;
string can be:
Any string: Defines a server name and an optional URI prefix. The server name allows the "*" symbol to be used at the beginning or end. When Nginx checks, the server port in the "Referer" request header is ignored.
Regular expression: must begin with a "~" symbol. It is important to note that the expression begins to match the text after "http:/" or "https://" to the
example .
valid_referers none blocked server_names # 定义请求报文referer首部不存在、为空或符合下面列出的两种主机名,为合法 *.example.com example.* www.example.org/galleries/ # 字符串匹配主机名 ~\.google\.; # 正则表达式匹配主机名 if ($invalid_referer) { # 定义合法referer首部之后,可使用内置变量invalid_referer作为条件,从而对非法referer首部的请求报文拒绝处理,比如返回403或重定向至另一位置 return 403;拒绝不合规的引用 }
Log related
Ngx_http_log_module introduced Directives Access_log, Log_format, Open_log_file_cache.
1, Access_log
Usage Range: HTTP segment, server segment, location segment, if statement in Location segment, limit_except directive
Use format:
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];access_log off;
The meaning of each parameter:
Parameter meaning
path specifies where to store the access. Different servers should of course be stored in different locations, otherwise difficult to view
format Specifies the log formats
BUFFER=SIZE specifies the buffer size. When there is a lot of concurrency, too late to write the log content to disk, then write in the buffer, cycle brush write to disk
FLUSH=TIME Specifies the period of time that the buffer content is brushed to disk
Gzip[=level] using compression and specifying levels
syslog:server= specifies that the logs reside on the Syslog server. such as syslog:server=192.168.1.1 and so on. To use syslog, this parameter needs to be placed in the front-end
Default value:
access_log logs/access.log combined # 默认,路径定义在编译安装时--prefix指定的路径下的logs/access.log下,格式为combined(这个格式定义同httpd的`)
Log_format
Use format: Log_format name string ..., define the log format name name, and define the fields for this format name.
Similar to httpd in the definition of the way, but httpd with a variety of macros, here is built-in variables.
Use Range: HTTP segment
Each built-in variable is basically known as the default definition for the combined format:
log_format combined ‘$remote_addr - $remote_user [$time_local] ‘ ‘"$request" $status $body_bytes_sent ‘ ‘"$http_referer" "$http_user_agent"‘;
The specific meaning of the built-in variables can be queried on the official website, do not repeat.
Open_log_file_cache
Use format:
open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];open_log_file_cache off;
Specifies whether to cache file descriptors for log files and improve the efficiency of opening log files to update log files. Closed by default.
Parameter meaning:
Parameter meaning
MAX=N Specifies the maximum number of cache entries. When the maximum number is reached, use the least Recently used algorithm (LRU) to clean up excess entries
INACTIVE=TIME specifies the inactivity duration. Default 10 seconds
MIN_USES=N Specifies the minimum number of times to be accessed during an inactive duration, otherwise it is considered an inactive cache (cleanup required)
VALID=TIME Specifies the validity check time, that is, how often to check whether the file that the cached file descriptor corresponds to exists or is renamed. Default 60 seconds
Error_log
The directive is in the Nginx core module core functionality, the above access log commands in the Ngx_http_log_module module.
It's written here because they're all logs. The error_log is used to define the error log.
Use range: main segment, HTTP segment, mail segment, stream segment, server segment, location segment
Use format:
Error_log File | [Syslog] | [STDERR] | [Memory] Level # file indicates the error date to which file is recorded;
can also be logged on a specified syslog server
# 也可输出至标准错误输出(stderr) # 也可记录在内存中(memory)。性能好但不会永久保存,一般调试时使用
Log level severity from low to High: Debug, info, notice, warn, error, crit, alert, Emerg
The information that is output at each level is the current level and information that is more severe than the level. However, to use the debug level, the –WITH-DEBUG option is specified at compile time.
Default configuration:
Error_log Logs/error.log Error
5. URL rewriting (http_rewrite_module)
⑴rewrite regex replacement [flag];
If the URI matches the specified regular expression, the URI is overwritten by the string defined by the replacement parameter. If the replacement string begins with "http:/" or "https://", nginx ends the execution process and returns a redirect to the client.
The flag parameter can be:
①last: Once the current rule is matched and rewritten, immediately stop checking for subsequent other rewrite rules, and then re-initiate the request through the rewritten rule
②break: Once the current rules are matched and rewritten immediately stop checking the subsequent rules of the other rewrite, and then continue to be followed by Nginx;
③redirect: Return 302 temporary Redirect, the browser will show the URL after the jump address
④permanent: Returns a 301 permanent redirect, and the browser displays the URL address after the jump.
Attention:
Last and break only implement URL rewriting, the URL address in the browser address bar is not changed, which is different from redirection.
The break flag is generally used when rewrite is written in the location, or the rewrite is written in the IF context
如果replacement字符串包括新的请求参数,以往的请求参数会添加到新参数后面。如果不希望这样,在replacement字符串末尾加一个问号“?”,就可以避免,例如: rewrite ^/users/(.*)$ /show?user=$1? last; 如果正则表达式中包含字符“}”或者“;”,整个表达式应该被包含在单引号或双引号的引用中,因这两个符号在nginx配置文件中有特殊意义。 示例: location / { root /www/b.org; rewrite ^/images/(.*)$ /imgs/$1 last; rewirte ^/imgs/(.*)$ /images/$1 last; } 上述用法会造成nginx重复10轮循环,然后返回错误500,应将last换成break
Rewrite_log On|off;
Whether to record the rewriting process in the error log, default to off; If enabled, the default is notice level;
The path to replace with IS "http://...", "https://..."
server { listen 80; server_name www.test.com; root /var/www; location /test1.html { rewrite /test1.html http://192.168.0.106/test2.html; }}
If
The IF directive is used to perform the relevant configuration, depending on whether the specified conditions are met.
Use format: if (condition) {...}
Scope of Use: Server segment, location segment
Common conditions
Conditional meaning
Variable name 8 variable value is null or 0 o'clock, which means "false"
= or! = Compares two variables equal or unequal
~ or!~ regular expression matches or does not match, case-sensitive. If there is "}", ";" characters, you need to use double or single quotation marks
~ or!~ Ibid, just case insensitive
-F or!-f a file exists or does not exist
-D or!-d a directory exists or does not exist
-E or!-e a file, directory, link file exists or does not exist
-X or!-x whether a file is executable
An example of an official documentation section:
if ($request_method = POST) { # 请求方法是POST时,返回405 return 405;}if ($slow) { # 内置变量slow为真时,限速10k limit_rate 10k;}if ($invalid_referer) { # 内置变量invalid_referer为真(即referer请求首部非法),返回403 return 403;} if (condition) { ... }
示例:
if ($http_user_agent ~ MSIE) { rewrite ^(.*)$ /msie/$1 break; } if ($invalid_referer) { return 403; }
Return
The command return indicates that the current processing is stopped and returned directly to the client.
Use format:
return code [text]; # returns the specified status code and reason phrase (i.e., Status code interpretation)
return code URL; # returns the specified status code and a URL. So this status code is generally specified as 301, 302, etc.
return URL; # Returns a URL directly, similar to redirecting the
Scope of Use: Server segment, location segment, if statement
6, view Nginx basic status information (Http_stub_status_module, non-standard module, need to be specified when compiling and installing Nginx)
Location/basic_status {
Stub_status on;
}
Content meaning:
1, active connections, active status of the number of connections.
Activity status includes: A connection has been established waiting to send a response message, the service is loading resources, sending a response message, etc.
There are at least 1 active status connections because the connection to the Status page is active at the moment the status page is accessed
2, the third line of 3 numbers are: The total number of requests received by the server, the total number of requests that have been processed, the total number of requests sent by the client.
3 numbers are all "already happened" connection information
The 3rd number is often the most because it contains all the requests sent by the client, including the number of requests received and processed by the server, as well as the number of requests that were not accepted or rejected for processing (such as access control, request method restrictions, etc.)
3. The last 3 numbers are: Reading is the number of connections that serve to correct the header of the read Request packet; The number of connections that writing to the sending response message; Waiting the number of connections waiting for the client to make a request (often long connection time not yet available, Wait for the client to next request).
The 3-digit statistics are "occurring" connection information. So their sum should be equal to the active connections
As HTTPS service side
Similar to the HTTPD configuration HTTPS service side, only the instructions are different. A single IP host can also be configured with only one HTTPS server.
The Ngx_http_ssl_module module also does not load by default, and you need to specify "–with-http_ssl_module" at compile time.
Common directives:
directive meaning
SSL On|off Specifies whether SSL is enabled. Similar to "SSL engine On|off" in httpd
Ssl_certificate file specifies the certificate files used by the current server
Ssl_certificate_key file specifies the private key files used by the current server
SSL_PROTOCOLS Specifies the version of the SSL protocol used, which is typically used by default
SSL_SESSION_CACHE Specifies whether to enable SSL session caching. Because the SSL session consumes resources, the cache can be used to cache the key information and save resources when the same client accesses it.
SSL_SESSION_TIMEOUT Specifies the timeout length of the SSL session cache (although it is literally like an SSL session timeout), the default is 5 minutes.
Other commands are easy to understand and mainly describe the following Ssl_session_cache parameters:
OFF: Does not use SSL caching and explicitly informs clients that SSL sessions are not reusable
None: "Politely" does not use the SSL cache, which informs the client that SSL sessions are reusable and does not actually cache session parameters. Default is None
Builtin [: Size]:openssl's built-in caching mechanism, each worker process is exclusive of a memory space as a cache.
Can specify size, default size is 20,480 sessions
This mechanism produces memory fragmentation, and if different worker processes process the same request, the contents of the previous worker process cache cannot be hit.
Shared [Name:size], as opposed to builtin, shared means that each worker process shares a memory space as a cache.
Using shared, to specify the cache name
The size, in bytes, can be specified. 1M of space caches 4,000 sessions
Although GKFX and builtin can be used simultaneously, such as Ssl_session_cache builtin:1000 shared:ssl:10m, it is better to use GKFX alone (Official document description).
Linux-nginx-2