Nginx Configuration Detailed

Source: Internet
Author: User
Tags epoll gz file sendfile nginx server

#定义Nginx运行的用户和用户组
User www www;

#nginx进程数, the recommended setting is equal to the total number of CPUs (typically equal to twice times the total number of cores or total cores of the CPU).
Worker_processes 4;

#指定错误日志的存放路径, the error logging level can be selected as: [Debug | info | notice | warn | error | crit//EMERGENCY]
Error_log/var/log/nginx/error.log info; #在后边添加类型 default in the logs directory of Nginx home directory

#用来指定进程id的存储文件位置.
#在Linux/unix, many programs, such as Nginx, will start multiple processes, and the signal will need to know which process to signal. Different processes have different PID (process ID). Writing a PID into a file can make it easier to send a signal. For example, to reload the Nginx configuration can be written like this: Kill-hup ' cat/path/to/nginx.pid '
Pid/var/run/nginx.pid;

#指定进程可以打开的最大描述符这个指令是指当一个nginx进程打开的最多文件描述符数目, the theoretical value should be the number of open files (ulimit-n) and the number of nginx processes, but the Nginx allocation request is not so uniform, so it is best to ulimit- The value of n remains the same. Now the number of open files opened in the Linux 2.6 kernel is 65535,worker_rlimit_nofile 65535 should be filled accordingly. This is because Nginx dispatch when the allocation request to the process is not so balanced, so if fill 10240, total concurrency reached 340,000 when there is a process may exceed 10240, this will return 502 error
Worker_rlimit_nofile 65535;

#工作模式与连接数上限
Events
{
#参考事件模型, use [kqueue | rtsig | epoll |/dev/poll | select | poll]; The Epoll model is a high-performance network I/O model in the Linux version 2.6 kernel, and if it runs on FreeBSD, it uses the Kqueue model.
#使用epoll的I/O model Supplemental Description: Similar to Apache, Nginx has different event models for different operating systems

Use Epoll;
#告诉nginx收到一个新连接通知后接受尽可能多的连接.
Multi_accept on;
#设置可由一个worker进程同时打开的最大连接数. If the above mentioned Worker_rlimit_nofile is set, we can set this value very high. Keep in mind that the maximum number of customers is also limited by the number of socket connections available to the system (~ 64K), so setting unrealistic high doesn't benefit worker_connections 2048;
#工作进程的最大连接数量, according to the hardware adjustment, and the previous work process together, as large as possible, but do not run the CPU to 100 on the line, the maximum number of connections per process allowed, theoretically each Nginx server maximum number of connections is worker_processes * worker_ Connections Keepalive_timeout 60;
Worker_connections 65535;
}

#设定http服务器
http
{
Include Mime.types; #文件扩展名与文件类型映射表 is just a directive that contains the contents of another file in the current file. Here we use it to load a series of MIME types that will be used later.
Default_type Application/octet-stream; #默认文件类型 Set the default Mime-type used by the file
#charset Utf-8 CharSet gb2312; Set the default character set in our header file
#并不会让nginx执行的速度更快, but it can turn off the Nginx version number in the error page, which is good for security
Server_tokens off
#sendfile指令指定nginx是否调用sendfile函数 (zero copy mode) to output the file, for normal applications, must be set to ON. If you are using a disk IO heavy load application for download, you can set it off to balance disk and network IO processing speed and reduce system uptime.
Sendfile on;
#此选项允许或禁止使用socke的TCP_CORK的选项, this option is only used when using Sendfile
Tcp_nopush on;
#告诉nginx不要缓存数据, but a section of the send-when you need to send data in a timely manner, you should set this property to the application, so that when sending a small piece of data information can not immediately get the return value.
Tcp_nodelay on;
#日志定义格式 log_format name format [format ...] name represents the format name that is defined for the format that is defined by the default format of combined

#系统日志设置
Log_format combined ' $remote _addr-$remote _user [$time _local] "$request" '
' $status $body _bytes_sent ' $http _referer '
' "$http _user_agent" $http _x_forwarded_for ';
#自定义日志格式设定
Log_format access ' $remote _addr-$remote _user [$time _local] "$request"
' $status $body _bytes_sent ' $http _referer '
' "$http _user_agent" $http _x_forwarded_for ';
# $remote _addr and $http_x_forwarded_for to record a customer's real IP
# $remote _user used to record remote client user names
# $time _local for recording access time and time zone
# $request used to record request URL with HTTP protocol
# $status is used to record the request status, for example: The status is 200 on success, 404 when the page is found
# $body _bytes_sent used to record the size of the file body content sent to the client
# $http _referer is used to record from which page the link was accessed.
# $http _user_agent to record information about the client browser

#默认combined格式的日志目录
#access_log/data1/logs/filename.log

#设置nginx是否将存储访问日志. Turn off this option to make read disk IO operations faster (Aka,yolo)
Access_log/var/log/nginx/ha97access.log access;
#语法access_log access_log Path [format [Buffer=size | off]]
#path表示日志文件的存放路径 format indicates the log format name that is set using the LOG_FORMAT directive
#buffer =size Indicates the size of the set memory buffer eg:buffer=32k
#关闭日志 Access_log off

Server_names_hash_bucket_size 128; #保存服务器名字的hash表是由指令server_names_hash_max_size和server_names_hash_bucket_size所控制的. The parameter hash bucket size is always equal to the size of the hash table and is a multiple of the processor cache size. After reducing the number of accesses in memory, it is possible to speed up the lookup of hash table key values in the processor. If a hash bucket size equals the size of a processor cache, the worst case lookup of a key is 2 in memory. The first is to determine the address of the storage unit, and the second is to find the key value in the storage unit. Therefore, if Nginx gives the hint to increase the hash max size or hash bucket size, the first thing is to increase the size of the previous parameter.
Large_client_header_buffers 4 64k; #客户请求头缓冲大小nginx默认会用client_header_buffer_size这个buffer来读取header值, if the header is too large, it will use Large_client_header_ Buffers to read if you set a small HTTP header/cookie over the General Assembly report 400 error Nginx Bad request line if the buffer is exceeded, an HTTP 414 error (URI Too Long) is reported Nginx accepts the longest HTTP header size must be larger than one buffer, or 400 HTTP error will be reported (Bad Request)
Keepalive_timeout 120; #给客户端分配keep-alive Link time-out. The server will close the link after this timeout period. We set it down to allow Ngnix to continue working for a longer period of time.
Reset_timedout_connection on; #告诉nginx关闭不响应的客户端连接. This will release the memory space occupied by that client.
Send_timeout 10; #指定客户端的响应超时时间. This setting is not used for the entire forwarder, but between two client read operations. If, during this time, the client does not read any data, Nginx closes the connection.
AutoIndex on; #开启目录列表访问, the appropriate download server, the default shutdown.

Client_header_buffer_size 32k; #客户端请求头部的缓冲区大小, this can be set according to your system paging size, generally a request header size will not exceed 1k, but because the general system paging is greater than 1k, so this is set to paging size. The paging size can be obtained with the command getconf pagesize. [[Email protected]~] #getconf PAGESIZE 4096 But there are client_header_buffer_size over 4k, but client_header_buffer_size the value must be set to " The integer multiple of the system paging size
Client_max_body_size 8m; # Set the size of files uploaded via Nginx
Client_header_timeout 10; #设置请求头的超时时间 we can also lower this setting.
Client_body_timeout 10; #设置请求体的超时时间 we can also lower this setting.
Client_body_buffer_size 512k; #如果把它设置为比较大的数值, such as 256k, it is normal to submit any image that is less than 256k, whether using Firefox or IE. If you comment on the instruction, using the default Client_body_buffer_size setting, which is twice times the size of the operating system page, 8k or 16k, the problem arises. Whether using firefox4.0 or IE8.0, submit a larger, 200k or so picture, all returned to the Internal Server error Error


#以下和反向代理中有对应解释
Client_body_buffer_size 512k;,
Proxy_connect_timeout 5;
Proxy_read_timeout 60;
Proxy_send_timeout 5;
Proxy_buffer_size 16k;
Proxy_buffers 4 64k;
Proxy_busy_buffers_size 128k;
Proxy_temp_file_write_size 128k;
Proxy_intercept_errors on; #表示使nginx阻止HTTP应答代码为400或者更高的应答


Tcp_nopush on; #防止网络阻塞
Tcp_nodelay on; #防止网络阻塞



Limit_conn_zone $binary _remote_addr zone=addr:5m; The parameters of the shared memory #置用于保存各种key (such as the current number of connections). 5m is 5 megabytes, this value should be set large enough to store (32k*5) 32byte State or (16k*5) 64byte state.
Limit_conn addr, #为给定的key设置最大连接数. Here key is addr, we set the value is 100, that is to say we allow each IP address at most simultaneously open has 100 connection

Open_file_cache max = 65535 inactive = 60s; #这个将为打开文件指定缓存, the default is not enabled, Max Specifies the number of caches, the recommended and open files are the same, inactive refers to how long the file has not been requested after the cache is deleted.
#open_file_cache指令中的inactive参数时间内文件的最少使用次数, if this number is exceeded, the file descriptor is always opened in the cache, as in the example above, if a file is not used once within inactive time, it will be removed
Open_file_cache_valid 80s; #这个是指多长时间检查一次缓存的有效信息.
Open_file_cache_min_uses 1;#
Open_file_cache_valid 30s; #在open_file_cache中指定检测正确信息的间隔时间.
Open_file_cache_min_uses 2; #定义了open_file_cache中指令参数不活动时间期间里最小的文件数.
Open_file_cache_errors on; #指定了当搜索一个文件时是否缓存错误信息, also includes adding files to the configuration again. We also include server modules, which are defined in different files. If your server module is not in these locations, you will have to modify this line to specify the correct location.




#FastCGI相关参数是为了改善网站的性能: Reduce resource usage and improve access speed. The following parameters can be understood by literal means.
Fastcgi_connect_timeout 300;
Fastcgi_send_timeout 300;
Fastcgi_read_timeout 300;
Fastcgi_buffer_size 64k; #buffer Cache
Fastcgi_buffers 4 64k;
Fastcgi_busy_buffers_size 128k;
Fastcgi_temp_file_write_size 128k;

#gzip模块 is to tell Nginx to send data in the form of gzip compression. This will reduce the amount of data we send. Gzip Compression module is Nginx is a self-brought module but the default state is that it is not enabled, Gzip compression module can be transferred to the Web server to the client's picture, HTML,JS and other data compression transmission, the maximum can reach about 80 The module can read a pre-compressed GZ file, which reduces the CPU resource consumption per request for gzip compression. When the module is enabled, Nginx first checks if there is a file at the end of GZ that requests a static file, and if so, returns the contents of the GZ file directly. In order to be compatible with browsers that do not support gzip, enabling the Gzip_static module must preserve both the original static file and the Gz file. In this case, the disk space will be greatly increased with a large number of static files. We can make use of Nginx's reverse proxy function to keep GZ files only.
gzip on; #开启gzip压缩输出
Gzip_disable "Msie6"; #为指定的客户端禁用gzip功能. We set it to IE6 or lower to make our solution broadly compatible.
Gzip_static on; #告诉nginx在压缩资源之前, find out if there are pre-gzip-processed resources. This requires you to pre-compress your files, allowing you to use the maximum compression ratio so that Nginx does not have to compress the files (for more detailed gzip_static information, please click here)
Gzip_proxied any; #允许或者禁止压缩基于请求和响应的响应流. We set it to any, which means that all requests will be compressed.
Gzip_min_length 1000; #设置对数据启用压缩的最少字节数. If a request is less than 1000 bytes, we'd better not compress it, because compressing these small data reduces the speed of all processes that handle this request.

Gzip_min_length 1k; #最小压缩文件大小
Gzip_buffers 4 16k; #压缩缓冲区
Gzip_http_version 1.0; #压缩版本 (default 1.1, front End If squid2.5 please use 1.0)
Gzip_comp_level 4; #设置数据的压缩等级. This level can be any number between 1-9, 9 is the slowest but the maximum compression ratio. We set it to 4, which is a more eclectic setting
Gzip_types text/plain application/x-javascript text/css application/xml; #设置需要压缩的数据格式. There are already some of the above examples, and you can add more formats.
#压缩类型, the default is already included text/html, so there is no need to write, write up will not have a problem, but there will be a warn.
Gzip_vary on;
#注: The path specified by Proxy_temp_path and Proxy_cache_path must be in the same partition

Proxy_temp_path/data0/proxy_temp_dir;
#设置Web缓存区名称为cache_one, the size of the memory cache is automatically cleared for content that is not accessed for 200mb,1 days, and the disk cache space size is 30GB.
Proxy_cache_path/data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;

include/etc/nginx/conf.d/*.conf;
include/etc/nginx/sites-enabled/*;
Limit_zone crawler $binary _remote_addr 10m; #开启限制IP连接数的时候需要使用

Upstream pasis.com {
#详细看 load Balancing in "Nginx comment. Doc"
#upstream的负载均衡, weight is a weight that can be defined based on machine configuration. The Weigth parameter represents weights, and the higher the weight, the greater the probability of being allocated.
Server 192.168.8.43:80 weight=1 max_fails=2 fail_timeout=30s;
Server 192.168.8.44:80 weight=1 max_fails=2 fail_timeout=30s;
Server 192.168.8.45:80 weight=1 max_fails=2 fail_timeout=30s;


}

#虚拟主机的配置
Server
{
#监听端口
Listen 80;
#域名可以有多个, separated by a space
server_name www.pasis.com pasis.com *.pasis.com;
Index index.html index.htm index.php;
Root/data/www/pasis; #存在的目录
Location ~* \.php${
Fastcgi_pass 127.0.0.1:9000; #指定FastCGI服务器监听端口与地址, can be a local or other
Fastcgi_index index.php;
Include fastcgi.conf;
}
#图片缓存时间设置
Location ~. *\. (gif|jpg|jpeg|png|bmp|swf) $
{
Expires 10d;
}
#JS和CSS缓存时间设置
Location ~. *\. (JS|CSS)? $
{
Expires 1h;
}

#对 "/" Enable reverse Proxy
Location/{
#这个指令设置被代理服务器的地址和被映射的URI, the address can be in the form of a host name or IP-plus port number
Proxy_pass http://127.0.0.1:88;
#如果需要修改从被代理服务器传来的应答头中的 the "location" and "Refresh" fields, which can be set with this instruction.
Proxy_redirect off;


Proxy_set_header Host $host;
Client_max_body_size 10m; #允许客户端请求的最大单文件字节数
Client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,

Proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间 Initiate handshake wait response time-out
Proxy_send_timeout 90; # #后端服务器数据回传时间_就是在规定时间之内后端服务器必须传完所有的数据
Proxy_read_timeout 90; #连接成功后_等候后端服务器响应时间_其实已经进入后端的排队之中等候处理 (can also be said to be the time the backend server processes the request)
Proxy_buffer_size 4k; #设置从被代理服务器读取的第一部分应答的缓冲区大小, typically this part of the answer contains a small answer header, which, by default, is the size of a buffer specified in instruction Proxy_buffers, but can be set to a smaller
Proxy_buffers 4 32k; The number and size of buffers #设置用于读取应答 (from the proxy server), which by default is paging size, may be 4k or 8k depending on the operating system
Proxy_busy_buffers_size 64k; #高负荷下缓冲大小 (proxy_buffers*2)
Proxy_temp_file_write_size 64k; #设置在写入proxy_temp_path时数据的大小 to prevent a worker process from blocking too long when passing files

#以下三行, the purpose is to upload the information received by the proxy server to the real server
Proxy_pass http://img_relay$request_uri;# #设置被代理服务器的端口或套接字, and 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; #后端的Web服务器可以通过X-forwarded-for get the user real IP

}
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;
}
[Email protected] {
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;
}
[Email protected] {
Access_log/data/logs/image.log log404;
Rewrite ^ (. *) $ http://211.151.188.190:8080/face.jpg redirect;
}

#设定查看Nginx状态的地址
Location/nginxstatus {
Stub_status on; #主要用于查看Nginx的一些状态信息
Access_log on; #访问日志
#以下是保护网站目录的访问
Auth_basic "Nginxstatus";
Auth_basic_user_file conf/htpasswd;
#htpasswd文件的内容可以用apache提供的htpasswd工具来产生.
}
#禁止访问. htxxx file
location~/\.ht {
Deny all;
}


#本地动静分离反向代理配置
#所有jsp的页面均交由tomcat或resin处理
Location ~. (JSP|JSPX|DO)? $ {
Proxy_set_header Host $host;
Proxy_set_header X-real-ip $remote _addr;
Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
Proxy_pass http://127.0.0.1:8080;
}
#所有静态文件由nginx直接读取不经过tomcat或resin
Location ~. *. (HTM|HTML|GIF|JPG|JPEG|PNG|BMP|SWF|IOC|RAR|ZIP|TXT|FLV|MID|DOC|PPT|PDF|XLS|MP3|WMA) $
{Expires 15d;}
Location ~. *. (JS|CSS)? $
{Expires 1h;}
}
}

Nginx Configuration Detailed

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.