nginx

实验环境

编译安装,根目录:/mnt/app/nginx/

配置文件

...								#main块

events {						#events块
   ...
}

http {							#http块				协议级别
    ...
    server {					#server块			服务级别
        ...
        location [PATTERN] {	#location块			请求级别
            ...
        }
        upstream [SERVERS] {	#upstream块
            ...
        }
    }
}

1 main块

配置影响nginx全局的指令。

1.1 基本属性

user USER [GROUP];
	# user nginx;
	# user nginx nginx;
	# nginx以指定属主属组运行
pid /PATH/nginx.pid;
	# pid logs/nginx.pid;
	# 进程pid文件

1.2 定位调试

daemon off|on;
	# daemon on;
	# 以守护进程方式启动nignx
master_process on|off;
	# master_process on;
	# 以master/worker方式运行nginx
error_log /PATH/error.log [level];
	# error_log logs/error.log;
	# error_log logs/error.log notice;
	# 错误日志文件
	# 日志级别:debug > info > notice > warn > error > crit > alert > emerg
include /PATH/server.conf;
	# include conf.d/server.conf;
	# 子配置文件

1.3 性能优化

worker_processes auto|cpu_nums;
    # worker_processes auto;
	# worker_processes 4;
	# worker进程个数 ≤ cpu个数,查看/proc/cpuinfo文件
	# cat /proc/cpuinfo | grep "processor" | wc -l
worker_cpu_affinity CPUMASK CPUMASK...;
	# worker_processes 4;	
	# worker_cpu_affinity 0001 0010 0100 1000
	# 4个worker进程,每个进程绑定1颗cpu
	#
	# worker_processes 2;
	# worker_cpu_affinity 0101 1010;
	# 2个worker进程,每个进程绑定2颗cpu
	#
	# 将worker进程绑定到CPU核心,每个worker进程对应一个二进制掩码,
	# 掩码的每一位对应一个CPU。
worker_priority nice;
	# worker_priority 0;
	# nice值:[-20, 19],worker进程优先级

2 events块

配置影响nginx服务器或与用户的网络连接。

2.1 select poll epoll

  1. select==>时间复杂度O(n)
    它仅仅知道了,有I/O事件发生了,却并不知道是哪那几个流(可能有一个,多个,甚至全部),我们只能无差别轮询所有流,找出能读出数据,或者写入数据的流,对他们进行操作。所以select具有O(n)的无差别轮询复杂度,同时处理的流越多,无差别轮询时间就越长。

  2. poll==>时间复杂度O(n)
    poll本质上和select没有区别,它将用户传入的数组拷贝到内核空间,然后查询每个fd对应的设备状态, 但是它没有最大连接数的限制,原因是它是基于链表来存储的。

  3. epoll==>时间复杂度O(1)
    epoll可以理解为event poll,不同于忙轮询和无差别轮询,epoll会把哪个流发生了怎样的I/O事件通知我们。所以我们说epoll实际上是事件驱动(每个事件关联上fd)的,此时我们对这些流的操作都是有意义的(复杂度降低到了O(1))。

2.2 连接选项

worker_connections n;
	# worker_connections 1024;
	# 每个worker进程响应的最大并发请求数
use epoll|select|poll;
	# use epoll;
	# 定义事件模型,最好由nginx自动选择
accept_mutex on|off
	# accept_mutex on
	# 打开互斥锁,nginx负载均衡,轮询调度用户请求
	# 当启用这个参数时,会使用互斥锁交替给worker进程分配新连接,
	# 否则话所有worker进程会争抢新连接,即或造成所谓的“惊群问题”,
	# 惊群问题会使nginx的空闲worker进程无法进入休眠状态,造成系统资源占用过多。
	# 启用此参数会一定程度上导致后台服务器负载不均衡,但是在高并发的情况下,
	# 关闭此参数可以提高nginx的吞吐量。
lock_file /PATH/file.lock;
	# lock_file logs/nginx.lock;
	# nginx的互斥锁文件,nginx使用锁的机制来实现accept_mutex功能和共享内存
	# 大多数操作系统中锁都是一个原子操作,这种情况下这条指令无效

3、http块

3.1 套接字相关

tcp_nodelay on | off
	# tcp_nodelay on;
	# http长连接状态下,http回包长度如果小于tcp的MSS,就会将多个回包合并成一个再回包。
	# 这样情况下,客户端前几次请求回同时到达,对于客户端来说存在时延。
	# MSS(Max Segment Size)及最大分片长度,tcp根据滑动窗口握手协商出来。
	# 开启tcp_nodelay,每个客户段request都会回复一个response。
sendfile on|off
	# sendfile on;
	# 启用sendfile机制
	#
	# 传统io
	# read()调用:磁盘数据→内核缓冲区→用户缓冲区
	# write()调用:用户缓冲区→内核缓冲区→socket协议栈
	# 一次io完整过程:磁盘数据→内核缓冲区→用户缓冲区→内核socket缓冲区→协议栈
	#
	# sendfile机制
	# sendfile()调用:磁盘数据→内核缓冲区→内核socket缓冲区→协议栈
	# 通过senfile机制,减少数据从内核空间到用户空间,再从用户空间到内核空间的拷贝,大大提高传输性能
tcp_nopush on|off
	# tcp_nopush on;
	# 在sendfile机制下,由于磁盘数据未经过用户空间,所以响应报文未经由用户空间nginx程序封装报头,报头需内核向nginx获取,tcp_nopush就是将http首部送到内核
log_format NAME 'str...'
	# log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    #                 '$status $body_bytes_sent "$http_referer" '
    #                 '"$http_user_agent" "$http_x_forwarded_for"';
    #
    # httpd的combined格式:
    # log_format mycombined '$remote_addr - $remote_user [$time_local] "$request" '
    #                     '$status $body_bytes_sent "$http_referer" "$http_user_agent"';
    #
    # $bytes_sent: 发送给客户端的字节数,含头部
    # $body_bytes_sent: 发送给客户端的字节数,不含头部
    # $connection: 连接序列号
    # $connection_requests: 通过当前连接发出的请求数量
    # $msec: 日志写入时间,单位为秒,精度是毫秒
    # $pipe: 如果请求是通过http流水线发送,则其值为"p",否则为“."
    # 	非流水线式:客户在收到一个响应后才能发送下一个请求
    # 	流水线式:客户在收到HTTP的响应报文之前能够接着发送新的请求报文。于是一个接一个的请求到达服务器后,服务器就可以连续的返回响应报文。
    # $request_length: 请求报文长度(含请求行、请求头、请求体)
    # $request_time: 请求处理时长,单位为秒,精度为毫秒
    # $status: 响应状态码
    # $time_iso8601: 标准格式的本地时间,形如"2020-03-13T18:31:27+08:00"
    # $time_local: 通用日志格式下的本地时间,形如"13/Mar/2020:18:31:27 +0800"
    # $http_referer: 请求的referer地址
    # $http_user_agent: 客户端浏览器信息
    # $remote_addr: 客户端IP
    # $remote_port: 客户端port
    # $http_x_forwarded_for: 当前端有代理服务器时,设置web节点记录客户端地址的配置,此参数生效的前提是代理服务器也要进行相关的x_forwarded_for设置
    # $request: 完整的原始请求行,如 "GET / HTTP/1.1"
    # $remote_user: 客户端认证用户名,针对启用了用户认证的请求
    # $request_uri: 完整的请求地址,如 "/index.php?share/commonJs&st=user&act=login"
    # $uri: 请求的文件路径,不包含”?”或者”#”之类的东西,如"/index.php"

3.2 资源请求相关

keepalive_timeout timeout
    # keepalive_timeout 65;
    # 长连接超时时长,0表示禁止长连接
keepalive_requests number
    # keepalive_requests 100;
    # 长连接时最大请求资源数量
send_timeout time
    # send_timeout 60;
    # 发送数据至客户端超时时长
client_max_body_size size
	# client_max_body_size 1m;
	# 客户端请求服务器上传文件最大允许大小,在“Content-Length”请求头中指定。如果请求的正文数据大于client_max_body_size,HTTP协议会报错 413 Request Entity Too Large。
client_body_buffer_size size
    # client_body_buffer_size 16k;
    # 用于接收客户端请求报文的body部分的缓冲区大小,如果post文件大于client_body_buffer_size小于client_max_body_size,其将被暂存到磁盘上的由client_body_temp_path指令所定义的位置
client_body_temp_path path [level1 [level2 [level3]]]
    # 关于client_body_temp目录的作用,简单说就是如果客户端POST一个比较大的文件,长度超过了nginx缓冲区的大小, 需要把这个文件的部分或者全部内容暂存到client_body_temp目录下的临时文件。
    # 设置临时文件存放路径。只有当上传的请求体超出缓存区大小时,才会写到临时文件中;路径要有可写权限
	#
	# client_body_temp_path /var/tmp/client_body 2 1 1
	# level1: 用1位16进制数字表示一级子目录;0-f
	# level2: 用2位16进程数字表示二级子目录:00-ff
	# level3: 用2位16进程数字表示三级子目录:00-ff

3.3 连接限制相关

3.3.1 rate设置
limit_rate rate
    # limit_rate 1k;
    # limit_rate 1m;
    # 限制响应客户端的传输速率,单位bytes/second,0表示不限制
limit_rate_after bytes
    # limit_rate 1024m;
    # 限制在传输多少bytes后限速
3.3.2 session限制
limit_conn_log_level info | notice | warn | error;
    # limit_conn_log_level error;
    # 达到最大限制连接数后,记录日志的等级
limit_conn_status code;
    # limit_conn_status 503;
    # 当超过连接限制后,返回的响应状态码,503服务暂不可用
limit_conn_zone key... zone=name:size;
    # limit_conn_zone $binary_remote_addr zone=per_con:10m;
    # 只能用在http块中,以ip和port为key,限制每个客户端同一时间的连接数
    #
    # key: 键,客户端标识
    # zone: 共享存储空间
    # size: 共享存储空间大小,ipv4是32位即4字节,ipv6是64位即8字节,10M可以存放10*1024*1024/8=1310720个ip即key
limit_conn 'name' 'num'
    # limit_conn per_con 1;
    # 限制连接per_con的session会话同时只能存在1个
3.3.3 request限制
limit_req_log_level info | notice | warn | error;
    # limit_conn_log_level error;
    # 达到最大限制请求数后,记录日志的等级
limit_req_status code;
    # limit_conn_status 503;
    # 当超过请求限制后,返回的响应状态码,503服务暂不可用
limit_req_zone key... zone=name:size rate='rate'r/s;
    # limit_req_zone $binary_remote_addr $remote_port zone=per_req:10m rate=1r/s;
    # 只能用在http块中,以ip和port为key,限制每秒的http请求为1个
    #
    # key: 键,客户端标识
    # zone: 共享存储空间
    # size: 共享存储空间大小
limit_req zone='name' [burst='num'] [nodelay];
    # limit_req zone=per_req burst=5 nodelay;
    # 限制每个session的缓冲队列为5,超过5个请求后直接丢弃
    #
    # burst: 缓冲队列长度,峰值
    # nodelay: 未设置时,请求排队等待;设置时,当请求数大于burst时,请求直接丢弃,不排队
3.3.4 完整限速配置
http {
    limit_conn_log_level error;
    limit_conn_status 503;
    limit_conn_zone $binary_remote_addr zone=per_con:1m;
    
    limit_req_log_level error;
    limit_req_status 503;
    limit_req_zone $binary_remote_addr zone=per_req:1m rate=10r/s;
}

server {
    listen 8080;
    server_name localhost;
    limit_conn per_con 1;
    limit_req zone=per_req burst=15 nodelay;
    limit_rate=300k;
}

3.4 压缩传输

gzip on | off
    # gzip on;
    # 使能gzip功能
gzip_comp_level level
    # gzip_comp_level 5;
    # 设置压缩比为5,压缩等级1-9
gzip_types mime-type ...
    # gzip_types text/css application/javascript;
    # 压缩过滤器,仅对此处设置的mime类型压缩,不支持通配符
gzip_min_length length
    # gzip_min_length 1k;
    # 压缩阈值,小于length的响应报文不压缩
gzip_buffers number size
    # gzip_buffers 4 16k
    # 申请4个16k大小内存作为压缩结果的缓冲区
gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any
    # gzip_proxied any;
    # Nginx作为反向代理的时候启用,开启或者关闭后端服务器返回的结果,匹配的前提是后端服务器必须要返回包含"Via"的 header头。  
    # off - 关闭所有的代理结果数据的压缩  
    # expired - 启用压缩,如果header头中包含 "Expires" 头信息  
    # no-cache - 启用压缩,如果header头中包含 "Cache-Control:no-cache" 头信息  
    # no-store - 启用压缩,如果header头中包含 "Cache-Control:no-store" 头信息  
    # private - 启用压缩,如果header头中包含 "Cache-Control:private" 头信息  
    # no_last_modified - 启用压缩,如果header头中不包含 "Last-Modified" 头信息  
    # no_etag - 启用压缩 ,如果header头中不包含 "ETag" 头信息  
    # auth - 启用压缩 , 如果header头中包含 "Authorization" 头信息  
    # any - 无条件启用压缩
gzip_vary on | off
    # gzip_vary on;
    # 在http header中添加Vary: Accept-Encoding
    # 告诉代理服务器缓存两种版本的资源:压缩和非压缩
gzip_disable regex ...;
    # gzip_disable "MSIE [1-6]\."
    # 根据表达式匹配到'User-Agent'字段的请求报文,响应时不压缩

压缩配置

# 模块: http_gzip_static_module
http {
    gzip on;
    gzip_comp_level 6;
    gzip_min_length 1k;
    gzip_proxied any;
    gzip_vary on;
    gzip_types text/html text/css text/xml text/plain image/gif image/jpeg image/png image/tiff image/webp image/x-icon application/x-httpd-php application/javascript application/json application/msword application/pdf application/postscript application/rtf application/xhtml+xmlaudio/mpeg audio/ogg video/3gpp video/mp4 video/mpeg video/quicktime video/webm video/x-flv video/x-ms-wmv video/x-msvideo;
}

# 测试:
curl -I -H "Accept-Encoding: gzip, deflate" "49.233.190.182:8080"

4、server块

listen PORT | ADDRESS[:PORT] | unix:/PATH/file.sock [default_server] [ssl]
	# listen 80 default_server
	# listen 10.10.10.10:443 ssl
server_name PATTERN
	# 精确匹配,通配符*匹配,正则匹配
	# 匹配顺序:精确匹配→左侧通配符匹配→右侧通配符匹配→正则匹配
	# server_name www.cr.com;
	# server_name *.cr.com;
	# server_name www.cr.*;
	# server_name ~^www.+\.cr\.com$;
access_log  /PATH/host.access.log  NAME
	# access_log logs/cr.access.log mycombined;
error_page CODE /CODE.html
	# error_page 500 502 503 504 /50x.html
	# location = /50x.html {
	#     root html
	# }
	# 50x.html路径:/mnt/app/nginx/html/50x.html
	# 当请求出现错误,nginx内部重定向指定页面,同时应为该页面指定映射路径
	#
	# 200:请求成功
	# 301:永久重定向
	# 302:临时重定向
	# 404:请求资源不存在
	# 500:服务器内部错误

4.1 ssl配置

server {
    listen       443 ssl;								#监听443端口
    server_name  localhost;

    ssl_certificate      cert.pem;						#证书文件
    ssl_certificate_key  cert.key;						#私钥文件

    ssl_session_cache    shared:SSL:1m;					#ssl的session缓存
    # ssl_session_cache off | none | [builtin[:size]] [shared:name:size]
    # builtin[:size]:使用OpenSSL内建的缓存,此缓存为每worker进程私有
    # [shared:name:size]:在各worker之间使用一个共享的缓存
    # 1M可以存放约4000个sessions
    ssl_session_timeout  5m;							#ssl的session超时时长
    #  客户端可以重用会话缓存中ssl参数的过期时间,即服务器和客户端交换密钥素材协商的加密密钥,这个素材即参数

    ssl_ciphers  HIGH:!aNULL:!MD5;						#ssl加密算法
    ssl_prefer_server_ciphers  on;						#首选服务器端ssl加密算法
    
	ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;	#ssl版本支持

    location / {
        root   html;
        index  index.html index.htm;
    }
}

4.2 rewrite配置

ngx_http_rewrite_module模块:将用户请求的URI基于regex所描述的模式进行检查,而后完成替换

rewrite regex replacement [flag]
    # 请求uri基于regex进行匹配替换为replacement
    # 如果在同一"块"中存在多个rewrite规则,会自顶向下检查,如果想要终止后续匹配,即可使用flag
    # 如果新URI字符中有关于协议的东西,如http://或者https://,进一步的处理就终止了,直接返回客户端302。
    # flag:
    # last: 终止rewrite匹配,并将此处重写的uri作为新的uri继续向下匹配location URL规则,提前重启新一轮循环。
    #break: 终止rewrite匹配,不在继续向下匹配location URL规则,避免重复rewite。因此,在server中使用last,而在location中使用break。。
    #redirect: 返回临时重定向302。该flag只有在"新URI"不是完整的URL地址时才会生效。
    #permanent: 返回永久重定向301。
return code [text]
return code URL
return URL
    # server {
    #     listen 80;
    #     return 301 https://www.new.comz:443$request_uri;
    # }
    # server {  #http重定向至https
    #     listen 443;
    # }
rewrite_log on | off
    # rewrite_log on;
    # 打开重写日志,日志写入error_log,级别位notice
    # 打开rewrite_log时应同时打开error_log
set $var value
    # location ~ ^/(\w*) {
         set $uri=$1;
     }
    # 定义变量
if (condition) { ... }
    # $args: 这个变量等于请求行中的参数,同$query_string
    # $content_length: 请求头中的Content-length字段。
    # $content_type: 请求头中的Content-Type字段。
    # $document_root: 当前请求在root指令中指定的值。
    # $host: 请求主机头字段,否则为服务器名称。
    # $http_user_agent: 客户端agent信息
    # $http_cookie: 客户端cookie信息
    # $limit_rate: 这个变量可以限制连接速率。
    # $request_method: 客户端请求的动作,通常为GET或POST。
    # $remote_addr: 客户端的IP地址。
    # $remote_port: 客户端的端口。
    # $remote_user: 已经经过Auth Basic Module验证的用户名。
    # $request_filename: 当前请求的文件路径,由root或alias指令与URI请求生成。
    # $scheme: HTTP方法(如http,https)。
    # $server_protocol: 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
    # $server_addr: 服务器地址,在完成一次系统调用后可以确定这个值。
    # $server_name: 服务器名称。
    # $server_port: 请求到达服务器的端口号。
    # $request_uri: 包含请求参数的原始URI,不包含主机名,如:”/api/data?arg=abc”。
    # $uri: 不带请求参数的当前URI,$uri不包含主机名,如”/html/abc.html”。
    # $document_uri: 与$uri相同。

condition:
    比较操作符
    # ==
    # !=
    # ~: 模式匹配,区分字符大小写;
    # ~*: 模式匹配,不区分字符大小写;
    # !~: 模式不匹配,区分字符大小写;
    # !~*: 模式不匹配,不区分字符大小写;
    
    文件及目录存在性判断
    # -e, !-e: 判断文件或目录是否存在,存在为真
    # -f, !-f: 判断是否为文件且存在,存在且为文件为真
    # -d, !-d: 判断是否为目录且存在,存在且为目录为真
    # -x, !-x: 判断是否位可执行文件且存在,存在且可执行为真

5、location块

location [= | ~ | ~* | !~ | !~* | ^~ | @] uri { ... }
	# location / { ...; }						#一般匹配,不带符号,匹配以"/"开头
	# location = /404.html { ...; }				#完全匹配,仅匹配"/404.html"
	# location ~ \.php$ { ...; }				#正则匹配,大小写敏感
	# location ~* \.(gif|jpg|jpeg)$ { ...; }	#正则匹配,忽略大小写
	# location !~ .xhtml$						#正则不匹配,大小写敏感,实际应用中不适用
	# location !~* .xhtml$						#正则不匹配,忽略大小写,实际应用中不适用
	# location ^~ /images/ { ...; }				#同一般匹配,匹配"/images/"开头的请求,一旦匹配将不再进行正则匹配,路径匹配永它
	# location @image { ...; }					#定义一个名为@image的location,实现内部跳转,用于error_page, try_files,
	#
	# 匹配顺序:完全匹配→正则匹配→一般匹配
	# =, ^~, ~, ~*, 不带符号
root /PATH
	# root html;
	# 设置根目录
alias /PATH
	# alias html
	# 设置路径别名,为绝对路径,且location匹配路径带"/",alias同样也应带"/"对应
	#
	# location中使用root和alias意义不同,且alias只能用于location,root能用于server、http和location
	# 例子:
	# 访问url1: www.cr.com/image/1.jpg
	# 访问url2: www.cr.com/images/1.jpg
	# 文件路径:/var/image/1.jpg
	# 要实现上面两个url映射到同一磁盘路径,显然root是不适合,如下所示:
	# location ~ ^/image/ { root /var/; }  #url的/image应出现在磁盘路径/var/下
	# location ~ ^/(image|images)/ { alias /var/iamge/; }  #url的/image和/images以别名方式映射到/var/iamge
index FILE
	# index index.html index.php;
	# 默认首页
try_files file ... uri;
try_files file ... =code;
    # location / { try_files $uri /index.php; }  #如果请求未找到文件返回首页
    # location / { try_files $uri =404; }  #如果请求未找到文件返回404
    #
    # location /img/ { try_files $uri @img; }  #如果请求未找到文件,去匹配对应location,并执行location中的规则
    # location @img {
    #     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 www.cr.com;
    # }
    #
    # 尝试查找给定file,如果未找到file则返回指定uri或code
limit_except method ... { ... }
    # limit_except GET {  #限制除了get方法外的其他方法
	#     allow 10.10.10.0/24;
	#     deny  all;
	# }
    # 根据指定方法名限制以外方法的用户请求
    # method: GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, or PATCH. 允许GET方法就意味着也允许HEAD方法

5.1 状态信息

模块: ngx_http_stub_status_module
编译: --with-http_stub_status_module
查看: nginx -V
配置: 
location /status {
    stub_status;
}

在这里插入图片描述

  • Active connections – 活动连接数
  • server accepts handled requests – nginx总共处理了3个连接, 成功创建3次握手 (相等表示中间没有失败的), 总共处理了3个请求 (平均每次握手处理了1个数据请求)。
  • Reading – nginx读取到客户端的Header信息数。
  • Writing – nginx返回给客户端的Header信息数。
  • Waiting – 开启keep-alive的情况下,这个值等于active - (reading + writing),意思就是Nginx说已经处理完正在等候下一次请求指令的驻留连接。

5.2 IP认证

模块: ngx_http_access_module
语法: allow address | CIDR | unix: | all;
     deny address | CIDR | unix: | all;
配置:
location /status {
    stub_status;
    deny 10.10.10.1;
    allow 10.10.10.0/24;
    deny all;
}

在这里插入图片描述

5.3 用户认证

模块: ngx_http_auth_basic_module
语法: auth_basic 'string' | off
     auth_basic_user_file 'file'  #绝对路径
配置: 
1、编辑配置文件
location /status {
    stub_status;
    auth_basic 'Admin zone'
    auth_basic_user_file /mnt/app/nginx/.ngxpass
}

2、安装htpasswd工具
yum -y install httpd-tools

3、生成.ngxpass
htpasswd -bc /mnt/app/nginx/.ngxpass cr 123

5.4 防盗链

#模块: ngx_http_referer_module
valid_referers none | blocked | server_names | string ...
    # 定义请求头referer首部的合法值,可以是无,空或给定字串
    # 当referer合法,$invalid_referer为真
    # none:请求报文首部没有referer首部
    # blocked:请求报文首部有referer首部,但可能无值或值为非完整url。referer字段应是一个完整的url,如: "http://xxx.com",而blocked就是可能经过某些防火墙后删除掉了schema即http://和https://,也就是所有的xxx.com或yyy.com,只要非完整url都满足
    # server_names: 即server_name定义得主机名
    # string: 任意字符串
    #     字符串,支持通配符
    #     正则表达式,以~开头
    #
    # location ~ ^/.*\.(gif|jpg|jpeg|png|bmp|swf|svg)$ {
    #     valid_referers none blocked server_names *.cr.com cr.com ~\.cr\.;
    #     if ($invalid_referer) {
    #     如果“Referer”请求标头字段值被视为有效,则为空字符串,否则为“1”。
    #         return 500;
    #         #rewrite ^/ /50x.html break;
    #     }
    # }
测试
#none: 没有none字段
[root@cr nginx]# curl http://49.233.190.182:8080/data/kali-light-4x3.png -I
HTTP/1.1 200 OK

#*.cr.com: http://www.cr.com视为有效
[root@cr nginx]# curl -e "http://www.cr.com" http://49.233.190.182:8080/img/kali-light-4x3.png -I
HTTP/1.1 200 OK
[root@cr nginx]# curl -e "http://www.baidu.com" http://49.233.190.182:8080/img/kali-light-4x3.png -I
HTTP/1.1 500 Internal Server Error

#blocked: 可以看出未带http和https的referer都视为有效
[root@cr nginx]# curl -e "www.cr.com" http://49.233.190.182:8080/img/kali-light-4x3.png -I
HTTP/1.1 200 OK
[root@cr nginx]# curl -e "www.baidu.com" http://49.233.190.182:8080/data/kali-light-4x3.png -I
HTTP/1.1 200 OK

5.5 代理

模块: ngx_http_proxy_module

proxy_pass URL
    # location /uri/ {
    #     proxy_pass http://host[:port];
    # }
    # http://HOSTNAME/uri/ --> http://host/uri/
    # 一般匹配时,proxy_pass不带uri时,会将location的uri传递至后端主机
    #
    # location /uri/ {
    #     proxy_pass http://host[:port]/new_uri;
    # }
    # http://HOSTNAME/uri/ --> http://host/new_uri/
    # 一般匹配时,proxy_pass带new_uri时,会使用proxy_pass的uri传递至后端主机
    #
    # location ~ /uri/ {
    #     proxy_pass http://host[:port];
    # }
    # http://HOSTNAME/uri/ --> http://host/uri/
    # 正则匹配时,proxy_pass不能带有uri,uri只能由location传递
proxy_set_header field value
    # proxy_set_header X-Real-IP  $remote_addr;
    # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    # 设置转发请求头部

完整配置

# 10.10.10.10
location / {
    proxy_pass http://10.10.10.11;
    proxy_set_header X-Real-IP "$remote_addr";
    proxy_set_header X-Forwarded-For "$remote_addr, $server_addr";
}

# 10.10.10.11
location / {
    proxy_pass http://10.10.10.20;
    proxy_set_header X-Forwarded-For "$http_x_forwarded_for, $server_addr";
}

#10.10.10.20
http{
……
    log_format  main  '$http_x_real_ip - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    server {
        location / {
            root   html;
            index  index.html index.htm;
            access_log logs/access.log main;
        }
    }
}

# logs
10.10.10.1 - - [22/Mar/2020:04:02:51 -0400] "GET / HTTP/1.0" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400" "10.10.10.1, 10.10.10.10, 10.10.10.11"

5.6 fastcgi

模块: ngx_http_fastcgi_module

fastcgi_pass address[:port]
    # fastcgi_pass 127.0.0.1:9000;
    # 请求代理至php-fpm监听的127.0.0.1:9000服务处理
fastcgi_index "str"
    # fastcgi_index index.php;
    # fastcgi默认主页
fastcgi_param parameter value
    # fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    # 传递给fastcgi服务参数

完整配置

location / {
            root html/kodexplorer;
            index index.php;
        }
location ~ \.php$ {
    root           html/kodexplorer;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;  #同nginx.conf在同一目录下
}

5.7 缓存设置

模块: ngx_http_headers_module

add_header name value [always]
# add_header X-Via  $server_addr;
# 自定义首部(http首部均使用http_name调用)
# $http_x_via调用该首部
#
# add_header Cache-Control: max-age=86400;
# 设置Cache-Control首部值
expires [modified] time
expires epoch | max | off
# location ~ \.(jpg|jpeg|png|svg|gif|bmp|swf)$ {
#     root        html/kodexplorer;
#     expires     3d;
# }
# 设置响应报文expires字段过期时间和cache-control过期时长
# time: 单位 s(秒) m(分) h(时) d(天)
#       如time为1d时
#           Cache-Control: max-age=86400
#           Expires: Wed, 23 Mar 2020 10:20:08 GMT (为系统当前时间加上time)
#       如time为-1时
#           Cache-Control: no-cache
#           Expires: Sat, 21 Mar 2020 10:29:55 GMT (为系统当前时间加上time,永久过期)      
# epoch: 指定“Expires”的值为 1 January,1970,00:00:01 GMT
#     Cache-Control: no-cache
#     Expires: Thu, 01 Jan 1970 00:00:01 GMT (为系统当前时间加上time,永久过期) 
# max: 
#     Cache-Control: max-age=315360000 (3650天)
#     Expires: Thu, 31 Dec 2037 23:55:55 GMT
# off: 不修改“Expires”和"Cache-Control"

6 upstream块

将多个后端服务器定义成组,后由proxy_pass,fastcgi_pass引用

server address [parameters]

parameters: 
    weight=number		
        #权重,默认为1
    max_fails=number	
        #连接失败后重新连接最大次数,超过最大次数后,该server标记不可用,默认1
    fail_timeout=time	
        #后端服务器器在指定超时时间内未做出回应,该server标记不可用,默认10s
    max_conns			
        #该服务器的最大并发连接数,0无限制
    backup				
        #设为备用服务器,所有后端服务器失效时启用该备用服务器
    down				
        #标记为不可用
least_conn
    加权最少连接wlc,当后端server连接相同时使用加权轮询wrr
hash key [consistent]
    根据key设置负载均衡调度算法,consistent为一致性hash
    # hash $remote_addr consistent;
ip_hash
    源地址hash负载均衡调度算法
keepalive number
    保持代理服务器和后端服务器之间一定长连接数量,减少创建连接的消耗,提升效率

完整配置:

# 10.10.10.10
location / {
    root html;
    index index.html;
}
# 10.10.10.11
location / {
    root html;
    index index.html;
}
# 10.10.10.20
server {
    listen 80;
    server_name localhost;
    location / {
        proxy_pass http://backend;
    }
    ……
}

upstream backend {
    server 10.10.10.10:80 weight=1 max_fails=1 fail_timeout=10;
    server 10.10.10.11:80 weight=1 max_fails=1 fail_timeout=10;
    server 10.10.10.20:8080 backup;
    hash $remote_addr consistent;
    keepalive 100;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值