整体结构
- 全局配置:将影响其他设置
- events:事件指令是设定Nginx的工作模式及连接数上限
- http
- upstream:负载均衡服务器设置
- sever:指定主机和端口
- location:URL匹配
...
events {}
http {
...
upstream {}
sever{
...
location xx{}
location xx{}
}
sever {}
}
全局配置
user nobody nobody;
worker_processes 2;
error_log logs/error.log notice;
pid logs/nginx.pid;
worker_rlimit_nofile 65535;
events{
use epoll;
worker_connections 65536;
}
user
:Nginx Worker
进程运行用户以及用户组,默认由nobody
账号运行。worker_processes
:Nginx要开启的进程数。error_log
:错误日志。日志输出级别有debug、info、notice、warn、error、crit。pid
: 指定进程pid的存储文件位置。worker_rlimit_nofile
: 同时连接的数量受限于系统上可用的文件描述符的数量
events
use
:Nginx支持的工作模式有select
、poll
、kqueue
、epoll
、rtsig
和/dev/poll
。其中select
和poll
都是标准的工作模式,kqueue
和epoll
是高效的工作模式,不同的是epoll
用在Linux平台上,而kqueue
用在BSD系统中。对于Linux系统,epoll
工作模式是首选。worker_connections
:工作进程数multi_accept
:默认是on,设置为on后,多个worker按串行方式来处理连接,也就是一个连接只有一个worker被唤醒,其他的处于休眠状态,设置为off后,多个worker按并行方式来处理连接,也就是一个连接会唤醒所有的worker,直到连接分配完毕,没有取得连接的继续休眠。服务器的吞吐量很大时,为了效率,可以关闭这个参数。
HTTP
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
log_format download '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_range" "$sent_http_content_range"';
client_max_body_size 20m;
client_header_buffer_size 32K;
large_client_header_buffers 4 32k;
Sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 60;
client_header_timeout 10;
client_body_timeout 10;
send_timeout 10;
}
Include
:媒体类型(include 在当前文件中包含另一个文件内容的指令),可以正确识别加载不同后缀的文件,这里是nginx中的mime.types文件。default_type
: 默认媒体类型,application/octet-stream
二进制流。sendfile
:on
开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。将tcp_nopush和tcp_nodelay两个指令设置为on用于防止网络阻塞;tcp_nopush
:on
必须在sendfile开启模式才有效,防止网路阻塞,积极的减少网络报文段的数量(将响应头和正文的开始部分一起发送,而不一个接一个的发送)。
日志
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
log_format download '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_range" "$sent_http_content_range"';
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
log_format
:指定http日志的输出格式。main为此日志输出格式的名称,可以在access_log指令中引用
其他
client_max_body_size 20m;
client_header_buffer_size 32K;
large_client_header_buffers 4 32k;
Sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 60;
client_header_timeout 10;
client_body_timeout 10;
send_timeout 10;
client_max_body_size
:用来设置允许客户端请求的最大的单个文件字节数;client_header_buffer_size
:用于指定来自客户端请求头的headerbuffer大小。对于大多数请求,1K的缓冲区大小已经足够,如果自定义了消息头或有更大的Cookie,可以增加缓冲区大小。这里设置为32K;large_client_header_buffers
:用来指定客户端请求中较大的消息头的缓存最大数量和大小, “4”为个数,“128K”为大小,最大缓存量为4个128K;keepalive_timeout
:设置客户端连接保持活动的超时时间。在超过这个时间之后,服务器会关闭该连接;client_header_timeout
:设置客户端请求头读取超时时间。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误;client_body_timeout
:设置客户端请求主体读取超时时间。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误,默认值是60;send_timeout
:指定响应客户端的超时时间。这个超时仅限于两个连接活动之间的时间,如果超过这个时间,客户端没有任何活动,Nginx将会关闭连接。
ZIP压缩
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
gzip
:开启或者关闭gzip模块,实时压缩输出数据流;gzip_min_length
:允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取。默认值是0,建议设置成大于1K的字节数,小于1K可能会越压越大;gzip_buffers
:表示申请4个单位为16K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果;gzip_http_version
:设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持GZIP解压,使用默认即可;gzip_comp_level
:指定GZIP压缩比,1 压缩比最小,处理速度最快;9 压缩比最大,传输速度快,但处理最慢,也比较消耗cpu资源;gzip_types
:指定压缩的类型,无论是否指定,“text/html”类型总是会被压缩的;gzip_vary
:选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用Squid缓存经过Nginx压缩的数据
upstream负载均衡
http {
...
upstream csdn.com{
ip_hash;
server 192.168.8.11:80;
server 192.168.8.12:80 down;
server 192.168.8.13:8009 max_fails=3 fail_timeout=20s;
server 192.168.8.146:8080;
}
...
}
支持 4 种调度算法,后两项属于第三方调度。
轮询(默认)
:每个请求按时间顺序逐一分配到不同的后端服务器,如果后端某台服务器宕机,故障系统被自动剔除,使用户访问不受影响;Weight
:指定轮询权值,Weight值越大,分配到的访问机率越高,主要用于后端每个服务器性能不均的情况下;ip_hash
:每个请求按访问IP的hash结果分配,这样来自同一个IP的访客固定访问一个后端服务器,有效解决了动态网页存在的session共享问题。当负载调度算法为ip_hash时,后端服务器在负载均衡调度中的状态不能是weight和backup。fair
:比上面两个更加智能的负载均衡算法。此种算法可以依据页面大小和加载时间长短智能地进行负载均衡,也就是根据后端服务器的响应时间来分配请求,响应时间短的优先分配。Nginx本身是不支持fair的,如果需要使用这种调度算法,必须下载Nginx的upstream_fair模块;url_hash
:按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,可以进一步提高后端缓存服务器的效率。Nginx本身是不支持url_hash的,如果需要使用这种调度算法,必须安装Nginx 的hash软件包。
server
指令指定后端服务器的IP地址和端口,同时还可以设定每个后端服务器在负载均衡调度中的状态。常用的状态有:
down
:表示当前的server暂时不参与负载均衡;backup
:预留的备份机器。当其他所有的非backup机器出现故障或者忙的时候,才会请求backup机器,因此这台机器的压力最轻;max_fails
:允许请求失败的次数,默认为1。当超过最大次数时,返回proxy_next_upstream 模块定义的错误;fail_timeout
:在经历了max_fails次失败后,暂停服务的时间。max_fails可以和fail_timeout一起使用。
server配置
http{
...
server{
listen 80;
server_name 192.168.8.18 cszhi.com;
index index.html index.htm index.php;
root /wwwroot/www.cszhi.com
charset gb2312;
access_log logs/www.ixdba.net.access.log main;
}
...
}
listen
:虚拟主机的服务端口server_name
:IP地址或者域名,多个域名之间用空格分开。index
:访问的默认首页地址root
:指定虚拟主机的网页根目录,这个目录可以是相对路径,也可以是绝对路径。Charset
:网页的默认编码格式。access_log
:指定此虚拟主机的访问日志存放路径。main
用于指定访问日志的输出格式。
https
server {
listen 443 ssl; //监听443端口,即ssl
server_name localhost;
ssl_certificate cert.pem;
ssl_certificate_key cert.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
ssl_certificate cert.pem
:指定pem文件路径ssl_certificate_key cert.key
:指定key文件路径ssl_session_cache shared:SSL:1m
:指定session cache大小ssl_session_timeout 5m
:指定session超时时间ssl_protocols TLSv1 TLSv1.1 TLSv1.2
:指定ssl协议ssl_ciphers HIGH:!aNULL:!MD5
:指定ssl算法ssl_prefer_server_ciphers on
:优先采取服务器算法
location URL匹配设置
根目录
location / {
root html;
index index.html index.htm;
}
网页默认指向路径打开,如https:baidu.com/,指向的html
>> html/index.html
。root
网页根目录,index
首页地址。
#1
location / {
try_files $uri $uri/ /index.php?$query_string;
}
#2
location / {
try_files $uri $uri/ @mongrel;
}
location @mongrel {
proxy_pass http://127.0.0.1:8080;
}
#3
location / {
try_files $uri $uri/ =404;
}
try_files
:按指定的file顺序查找存在的文件,并使用第一个找到的文件进行请求处理,查找路径是按照给定的root或alias为根路径来查找的,如果给出的file都没有匹配到,则重新请求最后一个参数给定的uri,就是新的location匹配,如果最后一个参数是 = 404 ,若给出的file都没有匹配到,则最后返回404的响应码$root
:是nginx配置的root
。前端文件放在nginx里的html文件夹里,即网页文件根目录,在这里为/usr/local/nginx/html
。$uri
:url相对路径,/
或/path
,/
等同于/index
。当用户请求http://localhost/example
时,$uri
是/example
,$uri/
指/example/index
。$query_string
: query参数
location / {
expires -1;
if_modified_since off;
add_header Last-Modified "";
add_header Cache-Control no-cache;
add_header Access-Control-Allow-Private-Network true;
etag off;
try_files $uri $uri/ /index.html;
}
设置不缓存,修改后更新。
expires -1
:不缓存
add_header
:添加请求头
以下为前端允许跨域设置:
#允许跨域请求的域,*代表所有
add_header 'Access-Control-Allow-Origin' *;
#允许带上cookie请求
add_header 'Access-Control-Allow-Credentials' 'true';
#允许请求的方法,比如 GET/POST/PUT/DELETE
add_header 'Access-Control-Allow-Methods' *;
#允许请求的header
add_header 'Access-Control-Allow-Headers' *;
proxy
location /api {
add_header Cache-Control no-cache;
add_header Pragma no-cache;
add_header Expires 0;
#1-无uri
proxy_pass http://localhost:8080;
#2-uri
proxy_pass http://localhost:8080/;
#
proxy_set_header Host $http_host
proxy_set_header X-Real-IP $remote_addr
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for
proxy_connect_timeout 30
proxy_send_timeout 60
proxy_read_timeout 60
}
proxy_pass
包含$uri
会被location规则匹配处理。
http://localhost:8080
>>http://localhost/api/param
http://localhost:8080/
>>http://localhost/param
proxy_pass
:服务器的地址( ip/域名/url地址 )proxy_set_header
:重新定义或者添加发往后端服务器的请求头proxy_set_header X-Real-IP
:启用客户端真实地址(否则日志中显示的是代理在访问网站)proxy_set_header X-Forwarded-For
:记录代理地址proxy_connect_timeout
:后端服务器连接的超时时间发起三次握手等候响应超时时间proxy_send_timeout
:后端服务器数据回传时间,在规定时间之内后端服务器必须传完所有的数据proxy_read_timeout
:nginx接收数据超时, 默认60s, 如果连续的60s内没有收到1个字节, 连接关闭,类似长连接。
$remote_addr
:浏览当前页面的用户计算机的ip地址。
X-Forwarded-For
: 简称XFF头,它代表客户端,也就是HTTP的请求端真实的IP
通过$remote_addr
只能获取到与服务器本身直连的上层请求ip,一般只在第一个代理上面设置proxy_set_header X-Real-IP $remote_addr
。如果是通过cdn访问过来的,后面web服务器获取到的,永远是cdn 的ip 而非用户ip,这个时候就要用X-Forwarded-For
了,这个变量从客户的真实ip为起点,穿过多层级的proxy ,最终到web 服务器,都会记录下来。proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for
来获取所有的代理ip 客户ip >>客户端IP,Nginx负载均衡服务器IP
。
$proxy_add_x_forwarded_for
和$http_x_forwarded_for
这两个的变量的值的区别在于,proxy_add_x_forwarded_for
比http_x_forwarded_for
多了一个$remote_addr
的值,$http_x_forwarded_for
浏览当前页面的用户计算机的网关。
错误页面
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
重定向。给错误代码,配置对应的错误页面。
静态文件
server{
...
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
root /wwwroot/www.csdn.com;
expires 30d;
}
...
}
所有扩展名以.gif
、.jpg
、.jpeg
、.png
、.bmp
、.swf
结尾的静态文件都交给nginx处理,而expires用来指定静态文件的过期时间,30d
是30天
文件夹
server{
...
location ~ ^/(upload|html)/ {
root /web/wwwroot/www.cszhi.com;
expires 30d;
}
...
}
upload和html路径下的文件都交给nginx处理,而expires用来指定静态文件的过期时间,30d
是30天。root 根目录。
动态文件
location ~ .*.php$ {
index index.php;
proxy_pass http://localhost:8080;
}
location是对此虚拟主机下动态网页的过滤处理,也就是将所有以.php为后缀的文件都交给本机的8080端口处理。
stream模块
stream模块一般用于tcp/UDP数据流的代理和负载均衡,可以通过stream模块代理转发TCP消息。 ngx_stream_core_module模块由1.9.0版提供。 默认情况下,没有构建此模块。 -必须使用-with stream配置参数启用。 也就是说,必须在使用./configure --with-stream编译时添加流模块。 流模块的使用方法与http模块相同,语法也基本相同。
stream{
upstream orderer-in {
server 10.211.56.4:7058;
}
server{
listen 10012;
proxy_pass orderer-in;
}
}
- 实现流量的代理转发。 这里所述的代理转发是指,只有一些端口服务被限制为活动IP地址。 例如,mysql账户一般将源地址限制为APP应用服务器,而nginx可能同时是web APP应用服务器。 开发人员需要验证一些数据库数据问题,但帐户的源地址有限制。 此时,通过在nginx中进行流传送,可以实现从开发终端向mysql的访问。
- 实现流量负载均衡。 有多个tcp或udp端口服务,如DNS。 流模块支持负载平衡算法,如轮询、最小连接数和ip_hash,从而实现数据流负载平衡。