A detailed explanation of the Nginx configuration file nginx.conf is as follows:
user nginx nginx ;
Nginx user and group: user group. Not specified under Windows.
worker_processes 8;
Worker processes: quantity. Adjust according to the hardware, usually equal to the number of CPUs or twice the number of CPUs.
error_log logs/error.log;
error_log logs/error.log notice;
error_log logs/error.log info;
Error log: storage path.
pid logs/nginx.pid;
pid (process identifier): storage path.
worker_rlimit_nofile 204800;
Specifies the maximum number of file descriptors a process can open: quantity.
This directive refers to the maximum number of file descriptors an nginx process can open. The theoretical value should be the maximum number of open files (ulimit -n) divided by the number of nginx processes, but nginx does not distribute requests that evenly, so it is best to keep it consistent with the value of ulimit -n.
Now, with the number of open files enabled as 65535 under the Linux 2.6 kernel, worker_rlimit_nofile should accordingly be set to 65535.
This is because nginx does not distribute requests evenly among processes during scheduling, so if you set it to 10240, when the total concurrency reaches 30,000 to 40,000, some processes may exceed 10240, and at that point a 502 error will be returned.
events
{
use epoll;
Uses the epoll I/O model. linux is recommended to use epoll, FreeBSD is recommended to use kqueue, and nothing is specified under Windows.
Additional notes:
Similar to apache, nginx has different event models for different operating systems
A) Standard event model
Select and poll belong to the standard event model. If no more efficient method exists on the current system, nginx will choose select or poll.
B) Efficient event model
Kqueue: used on FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0, and MacOS X. Using kqueue on dual-processor MacOS X systems may cause kernel crashes.
Epoll: used on systems with Linux kernel version 2.6 and later.
/dev/poll: used on Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+, and Tru64 UNIX 5.1A+.
Eventport: used on Solaris 10. To prevent kernel crash issues, it is necessary to install security patches.
worker_connections 204800;
The maximum number of connections for each worker process. Adjust it according to your hardware and use it together with the worker processes above. Set it as high as possible, as long as the CPU does not run at 100%. The maximum number of connections allowed per process. In theory, the maximum number of connections for each nginx server is. worker_processes*worker_connections
keepalive_timeout 60;
keepalive timeout period.
client_header_buffer_size 4k;
The buffer size for the client request header. This can be set according to your system page size. Generally, a request header will not exceed 1k, but since the page size of most systems is greater than 1k, it is set here to the page size.
The page size can be obtained with the command getconf PAGESIZE.
[[email protected] ~]# getconf PAGESIZE
4096
However, there are also cases where client_header_buffer_size exceeds 4k, but the value of client_header_buffer_size must be set to an integer multiple of the “system page size.”
open_file_cache max=65535 inactive=60s;
This specifies a cache for open files; by default it is not enabled. max specifies the number of cached entries, and it is recommended to match it with the number of open files. inactive indicates how long a file can go unrequested before it is removed from the cache.
open_file_cache_valid 80s;
This indicates how often to check the valid information of the cache.
open_file_cache_min_uses 1;
The minimum number of times a file must be used within the inactive time specified by the open_file_cache directive. If this number is exceeded, the file descriptor remains open in the cache. In the example above, if a file is not used even once within the inactive period, it will be removed.
}
##Set up the http server and use its reverse proxy feature to provide load balancing support
http
{
include mime.types;
Set the mime types; the types are defined by the mime.type file
default_type application/octet-stream;
log_format main
‘$remote_addr – $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for”‘;
log_format log404
‘$status [$time_local] $remote_addr $host$request_uri $sent_http_location’;
Log format settings.
$remote_addr and $http_x_forwarded_for are used to record the client’s IP address;
$remote_user: used to record the client username;
$time_local: used to record the access time and time zone;
$request: used to record the request URL and HTTP protocol;
$status: used to record the request status; success is 200,
$body_bytes_sent: records the size of the body content sent to the client;
$http_referer: used to record which page the link came from;
$http_user_agent: records information related to the client’s browser;
Usually, the web server is placed behind a reverse proxy, so the client’s IP address cannot be obtained directly. The IP address obtained through $remote_add is the IP address of the reverse proxy server. When forwarding the request, the reverse proxy server can add x_forwarded_for information to the HTTP header to record the original client’s IP address and the server address originally requested by the client.
access_log logs/host.access.log main;
access_log logs/host.access.404.log log404;
After using the log_format directive to set the log format, you need to use the access_log directive to specify the storage path of the log file;
server_names_hash_bucket_size 128;
#The hash table that stores server names is controlled by the directives server_names_hash_max_size and server_names_hash_bucket_size. The hash bucket size parameter is always equal to the size of the hash table and is a multiple of the processor cache size. By reducing the number of memory accesses, it becomes possible to speed up lookup of hash table keys in the processor. If the hash bucket size equals the size of one processor cache line, then in the worst case the number of memory lookups when searching for a key is 2. The first is to determine the address of the storage unit, and the second is to search for the key value in the storage unit. Therefore, if Nginx prompts that hash max size or hash bucket size needs to be increased, the first priority is to increase the former parameter.
client_header_buffer_size 4k;
The buffer size for the client request header. This can be set according to your system page size. Generally, the header size of a request will not exceed 1k, but since the page size of most systems is greater than 1k, it is set here to the page size. The page size can be obtained with the command getconf PAGESIZE.
large_client_header_buffers 8 128k;
Client request header buffer size. By default, nginx uses the client_header_buffer_size buffer to read header values; if
the header is too large, it will use large_client_header_buffers to read it.
open_file_cache max=102400 inactive=20s;
This directive specifies whether the cache is enabled.
Example: open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
open_file_cache_errors
Syntax: open_file_cache_errors on | off Default: open_file_cache_errors off Context: http, server, location This directive specifies whether cache errors are recorded when searching for a file.
open_file_cache_min_uses
Syntax: open_file_cache_min_uses number Default: open_file_cache_min_uses 1 Context: http, server, location This directive specifies the minimum number of files that can be used within a certain period among the inactive parameters of the open_file_cache directive. If a larger value is used, file descriptors in the cache remain always open.
open_file_cache_valid
Syntax: open_file_cache_valid time Default: open_file_cache_valid 60 Context: http, server, location This directive specifies when the validity information of cached items in open_file_cache needs to be checked.
client_max_body_size 300m;
Sets the size limit for files uploaded through nginx
sendfile on;
The sendfile directive specifies whether nginx calls the sendfile function (zero-copy mode) to output files. For ordinary applications, it must be set to on. If it is used for disk IO-intensive applications such as downloads, it can be set to off to balance disk and network IO processing speeds and reduce system uptime.
tcp_nopush on;
This option enables or disables the socket TCP_CORK option, and it is used only when sendfile is enabled
proxy_connect_timeout 90;
Timeout for connecting to the backend server — the timeout for initiating the handshake and waiting for a response
proxy_read_timeout 180;
After the connection is established, this is the time to wait for a response from the backend server — in fact, the request has already entered the backend queue and is waiting to be processed (it can also be understood as the time the backend server takes to process the request)
proxy_send_timeout 180;
Time for the backend server to return data — that is, within the specified time, the backend server must finish transmitting all the data
proxy_buffer_size 256k;
Sets the buffer size for reading the first part of the response from the proxied server. Usually, this part of the response contains a small response header. By default, this value is the size of one buffer specified by the proxy_buffers directive, but it can be set smaller
proxy_buffers 4 256k;
Sets the number and size of buffers used for reading responses (from the proxied server). By default, this is also the page size, which may be 4k or 8k depending on the operating system
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
Sets the size of data written to proxy_temp_path to prevent a worker process from being blocked too long while transferring files
proxy_temp_path /data0/proxy_temp_dir;
The paths specified by proxy_temp_path and proxy_cache_path must be on the same partition
proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
#Set the memory cache size to 200MB; content that has not been accessed for 1 day is automatically cleared; the disk cache size is 30GB.
keepalive_timeout 120;
keepalive timeout.
tcp_nodelay on;
client_body_buffer_size 512k;
If it is set to a relatively large value, such as 256k, then whether you use Firefox or IE to submit any image smaller than 256k, everything works normally. If this directive is commented out and the default client_body_buffer_size setting is used instead—that is, twice the operating system page size, 8k or 16k—the problem appears.
Whether using Firefox 4.0 or IE8.0, submitting a relatively large image of around 200k returns a 500 Internal Server Error
proxy_intercept_errors on;
This means enabling nginx to intercept HTTP responses with status codes of 400 or higher.
upstream bakend {
server 127.0.0.1:8027;
server 127.0.0.1:8028;
server 127.0.0.1:8029;
hash $request_uri;
}
nginx upstream currently supports 4 distribution methods
1. Round robin (default)
Requests are assigned one by one to different backend servers in chronological order. If a backend server goes down, it is automatically removed.
2. weight
Specifies the polling ratio. The weight is proportional to the access ratio and is used when backend server performance is uneven.
For example:
upstream bakend {
server 192.168.0.14 weight=10;
server 192.168.0.15 weight=10;
}
2. ip_hash
Each request is assigned according to the hash result of the client’s IP, so each visitor is fixed to one backend server, which can solve session issues.
For example:
upstream bakend {
ip_hash;
server 192.168.0.14:88;
server 192.168.0.15:80;
}
3. fair (third-party)
Requests are assigned according to the response time of the backend servers, with shorter response times getting priority.
upstream backend {
server server1;
server server2;
fair;
}
4. url_hash (third-party)
Requests are assigned according to the hash result of the accessed URL, so each URL is directed to the same backend server. This is particularly effective when the backend servers are used for caching.
Example: add a hash statement in upstream; other parameters such as weight cannot be written in the server statement. hash_method is the hash algorithm used
upstream backend {
server squid1:3128;
server squid2:3128;
hash $request_uri;
hash_method crc32;
}
tips:
upstream bakend{#Define the IPs and device status of the load balancing devices}{
ip_hash;
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 the following in the server where load balancing is needed
proxy_pass http://bakend/;
The status of each device is set as follows:
1.down means the current server temporarily does not participate in load balancing
2.weight: the larger the weight value, the greater the load balancing weight.
3.max_fails: the number of allowed request failures, default is 1. When the maximum is exceeded, the error defined by the proxy_next_upstream module is returned
4.fail_timeout: the pause time after max_fails failures.
5.backup: when all other non-backup machines are down or busy, requests go to the backup machine. So this machine will have the lightest load.
nginx supports configuring multiple sets of load balancing at the same time for different servers.
Setting client_body_in_file_only to On can record client POST data into a file for debugging
client_body_temp_path sets the directory for recorded files, and up to 3 levels of directories can be configured
location matches URLs. It can perform redirection or a new proxy/load balancing
##Configure the virtual machine
server
{
listen 80;
Configure the listening port
server_name image.***.com;
Configure the access domain name
location ~* .(mp3|exe)$ {
Load balance addresses ending with “mp3 or exe”
proxy_pass http://img_relay$request_uri;
Set the port or socket of the proxied server, as well as the URL
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
The purpose of the above three lines is to pass the user information received by the proxy server to the real server
}
location /face {
if ($http_user_agent ~* “xnp”) {
rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;
}
proxy_pass http://img_relay$request_uri;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
error_page 404 502 = @fetch;
}
location @fetch {
access_log /data/logs/face.log log404;
rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;
}
location /image {
if ($http_user_agent ~* “xnp”) {
rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;
}
proxy_pass http://img_relay$request_uri;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
error_page 404 502 = @fetch;
}
location @fetch {
access_log /data/logs/image.log log404;
rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;
}
}
##Other examples
server
{
listen 80;
server_name *.***.com *.***.cn;
location ~* .(mp3|exe)$ {
proxy_pass http://img_relay$request_uri;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
if ($http_user_agent ~* “xnp”) {
rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;
}
proxy_pass http://img_relay$request_uri;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#error_page 404 http://i1.***img.com/help/noimg.gif;
error_page 404 502 = @fetch;
}
location @fetch {
access_log /data/logs/baijiaqi.log log404;
rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;
}
}
server
{
listen 80;
server_name *.***img.com;
location ~* .(mp3|exe)$ {
proxy_pass http://img_relay$request_uri;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
if ($http_user_agent ~* “xnp”) {
rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif;
}
proxy_pass http://img_relay$request_uri;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#error_page 404 http://i1.***img.com/help/noimg.gif;
error_page 404 = @fetch;
}
#access_log off;
location @fetch {
access_log /data/logs/baijiaqi.log log404;
rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;
}
}
server
{
listen 8080;
server_name ngx-ha.***img.com;
location / {
stub_status on;
access_log off;
}
}
server {
listen 80;
server_name imgsrc1.***.net;
root html;
}
server {
listen 80;
server_name ***.com w.***.com;
# access_log /usr/local/nginx/logs/access_log main;
location / {
rewrite ^(.*)$ http://www.***.com/ ;
}
}
server {
listen 80;
server_name *******.com w.*******.com;
# access_log /usr/local/nginx/logs/access_log main;
location / {
rewrite ^(.*)$ http://www.*******.com/;
}
}
server {
listen 80;
server_name ******.com;
# access_log /usr/local/nginx/logs/access_log main;
location / {
rewrite ^(.*)$ http://www.******.com/;
}
}
location /NginxStatus {
stub_status on;
access_log on;
auth_basic “NginxStatus”;
auth_basic_user_file conf/htpasswd;
}
#Set the address for viewing Nginx status
location ~ /.ht {
deny all;
}
#Deny access to .htxxx files
}
Note: Variables
The Ngx_http_core_module module supports built-in variables whose names are the same as Apache’s built-in variables.
First, there are the lines in the client’s request header, such as $http_user_agent, $http_cookie, and so on.
In addition, there are some other variables
$args This variable is equal to the parameters in the request line
$content_length is equal to the value of “Content_Length” in the request line.
$content_type is equivalent to the value of “Content_Type” in the request header
$document_root is equivalent to the value specified by the root directive for the current request
$document_uri is the same as $uri
$host is the same as the value specified in the “Host” line of the request header, or the name of the server the request reached (if there is no Host line)
$limit_rate allows the connection rate to be limited
$request_method is equivalent to the request method, usually “GET” or “POST”
$remote_addr client IP
$remote_port client port
$remote_user is equivalent to the username, authenticated by ngx_http_auth_basic_module
$request_filename is the pathname of the file currently requested, formed by combining root or alias with the request URI
$request_body_file
$request_uri the complete original URI including parameters
$query_string is the same as $args
$sheeme http scheme (http, https), only when required for evaluation, for example
Rewrite ^(.+)$ $sheme://example.com$; Redirect;
$server_protocol is equivalent to the request protocol, using “HTTP/” or “HTTP/”
the server IP that the $server_addr request reaches; generally, the purpose of obtaining this variable’s value is to perform a system call. To avoid a system call, it is necessary to specify the IP in the listen directive and use the bind parameter.
$server_name the server name that the request reaches
$server_port the port number of the server that the request reaches
$uri is equivalent to the URI in the current request and may differ from the initial value, for example during internal redirection or when using index