一、安装

1.安装编译工具及库文件

yum -y install make zlib zlib-devel gcc-c++ libtool  openssl openssl-devel

2.解压

tar -zxvf nginx.nginx-1.16.1.tar.gz

3.编译,并指定目录

./configure --prefix=/usr/local/nginx
make && make install

4.启动

cd /usr/local/nginx/sbin
## 启动
./nginx
## 停止
./nginx -s stop

二、反向代理

## 修改配置文件nginx.conf
server {
        listen       80;
        server_name  localhost;
		# 
        location / {
            proxy_pass   http://127.0.0.1:8080;
            index  index.html index.htm;
        }
    }

三、负载均衡

五种负载均衡策略

1.轮训(default):根据时间顺序分配不同服务器

2.权重:指定轮训机率,weight和访问比率成正比

3.Ip绑定:固定ip访问

4.fair:第三方,根据服务响应时间分配

5.url_hash:第三方,按访问url的hash结果来分配请求 ,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效

Nginx负载均衡提供上游服务器(真实业务逻辑访问的服务器),负载均衡、故障转移、失败重试、容错、健康检查等。

当上游服务器(真实业务逻辑访问的服务器)发生故障时,可以转移到其他上游服务器(真实业务逻辑访问的服务器)。

1.upstream server配置

1.1 轮训

###定义上游服务器(需要被nginx真实代理访问的服务器) 默认是轮训机制
upstream  backServer{
	server 127.0.0.1:8080;
	server 127.0.0.1:8081;
}

server {
	listen       80;
	server_name  localhost;
	location / {
		### 指定上游服务器负载均衡服务器
		proxy_pass http://backServer;
		index  index.html index.htm;
	}
}

1.2 权重

 upstream  backServer{
    server 127.0.0.1:8080 weight=1;
    server 127.0.0.1:8081 weight=2;
}
	
server {
       listen       80;
       server_name  localhost;
       location / {
	    ### 指定上游服务器负载均衡服务器
	    proxy_pass http://backServer;
           index  index.html index.htm;
       }
   }

nginx.conf详解

##代码块中的events、http、server、location、upstream等都是块配置项##
##块配置项可以嵌套。内层块直接继承外层快,例如:server块里的任意配置都是基于http块里的已有配置的##
 
##Nginx worker进程运行的用户及用户组 
#语法:user username[groupname]    默认:user nobody nobody
#user用于设置master进程启动后,fork出的worker进程运行在那个用户和用户组下。当按照"user username;"设置时,用户组名与用户名相同。
#若用户在configure命令执行时,使用了参数--user=usergroup 和 --group=groupname,此时nginx.conf将使用参数中指定的用户和用户组。
#user  nobody;
 
##Nginx worker进程个数:其数量直接影响性能。
#每个worker进程都是单线程的进程,他们会调用各个模块以实现多种多样的功能。如果这些模块不会出现阻塞式的调用,那么,有多少CPU内核就应该配置多少个进程,反之,有可能出现阻塞式调用,那么,需要配置稍多一些的worker进程。
worker_processes  1;

##绑定Nginx worker进程到指定的CPU内核
#语法:worker_cpu_affinity cpumask[cpumask...]
#例如有4个CPU内核
#worker_cpu_affinity 1000 0100 0010 0001;
 
##ssl硬件加速。
#用户可以用OpneSSL提供的命令来查看是否有ssl硬件加速设备:openssl engine -t
#ssl_engine device;

##系统调用gettimeofday的执行频率
#语法: timer_resolution t

##Nginx worker进程优先级设置
#语法: worker_priority nice;
#默认: worker_priority 0;

##守护进程(daemon)。是脱离终端在后台允许的进程。它脱离终端是为了避免进程执行过程中的信息在任何终端上显示。这样一来,进程也不会被任何终端所产生的信息所打断。##
##关闭守护进程的模式,之所以提供这种模式,是为了方便跟踪调试nginx,毕竟用gdb调试进程时最繁琐的就是如何继续跟进fork出的子进程了。##
##如果用off关闭了master_proccess方式,就不会fork出worker子进程来处理请求,而是用master进程自身来处理请求
#daemon off;   #查看是否以守护进程的方式运行Nginx 默认是on
#master_process off; #是否以master/worker方式工作 默认是on
 
##error日志的设置#
#语法: error_log /path/file level;
#默认: error_log / log/error.log error;
#当path/file 的值为 /dev/null时,这样就不会输出任何日志了,这也是关闭error日志的唯一手段;
#leve的取值范围是debug、info、notice、warn、error、crit、alert、emerg从左至右级别依次增大。
#当level的级别为error时,error、crit、alert、emerg级别的日志就都会输出。大于等于该级别会输出,小于该级别的不会输出。
#如果设定的日志级别是debug,则会输出所有的日志,这一数据量会很大,需要预先确保/path/file所在的磁盘有足够的磁盘空间。级别设定到debug,必须在configure时加入 --with-debug配置项。
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

##用来帮助用户跟踪调试Nginx 接收两个参数stop和abort 通常不会使用
#stop Nginx的代码执行到这些调试点就会发出SIGSTOP信号以用于调试
#abort 会产生一个coredump文件,可以使用gdb来查看Nginx当时的各种信息
#debug_points point[stop|abort]

##限制coredump核心转储文件的大小
#Nginx强制停止,将信息存储在core文件中,以做调试使用。一个core文件可能达到几GB,所以需要加以限制
#语法:worker_rlimit_core size
#worker_rlimit_core 1g;

##指定coredump文件生成目录
#语法:working_directory path;
#working_directory ./core;

##指定Nginx worker进程可以打开的最大句柄描述符个数
#语法:worker_rlimit_nofile limit

##设置每个用户发往Nginx的信号队列的大小。
#也就是说用户的信号队列满了,再发送就会被丢失
#语法:worker_rlimit_sigpending limit;

##pid文件(master进程ID的pid文件存放路径)的路径
#pid        logs/nginx.pid;

##定义环境变量
#语法:env VAR|VAR=VALUE
#env TESTPATH=/tmp/;

##是否打开accept锁 accept_mutex是Nginx的负载均衡锁
#语法: accept_mutex[on|off]
#默认: accept_mutext on;

##lock文件的路径
#语法: lock_file path/file;
#默认: lock_file logs/nginx.lock;

##使用accept锁后到真正建立连接之间的延迟时间
#语法: accept_mutex_delay Nms;
#默认: accept_mutex_delay 500ms;

##批量建立新连接
#语法: multi_accept[on|off];
#默认: multi_accept off;

##选择事件模型 
#语法: use[kqueue|rtsig|epoll|/dev/poll|select|poll|eventport];
#默认: Nginx会自动使用最适合的事件模型。
#对于Linux操作系统来说, 可供选择的事件驱动模型有poll、 select、 epoll三种。 epoll当
然是性能最高的一种,

events {
 	#仅对指定的客户端输出debug级别的日志: 语法:debug_connection[IP|CIDR]
 	#这个设置项实际上属于事件类配置,因此必须放在events{……}中才会生效。它的值可以是IP地址或者是CIRD地址。
 	#debug_connection 10.224.66.14;  #或是debug_connection 10.224.57.0/24
 	#这样,仅仅以上IP地址的请求才会输出debug级别的日志,其他请求仍然沿用error_log中配置的日志级别。
 	#注意:在使用debug_connection前,需确保在执行configure时已经加入了--with-debug参数,否则不会生效。
 	##每个worker的最大连接数
	worker_connections  1024;
}
 
##核心转储(coredump):在Linux系统中,当进程发生错误或收到信号而终止时,系统会将进程执行时的内存内容(核心映像)写入一个文件(core文件),以作为调试只用,这就是所谓的核心转储(coredump).
 
http {
	##嵌入其他配置文件 语法:include /path/file
	#参数既可以是绝对路径也可以是相对路径(相对于Nginx的配置目录,即nginx.conf所在的目录)
    include       mime.types;
    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"';
 
    #access_log  logs/access.log  main;
 
    sendfile        on;
    #tcp_nopush     on;
 
    #keepalive_timeout  0;
    keepalive_timeout  65;
 
    #gzip  on;
 
    server {
		##listen监听的端口
		#语法:listen address:port [ default(deprecated in 0.8.21) | default_server | [ backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind | ssl ] ]
		#default_server: 如果没有设置这个参数,那么将会以在nginx.conf中找到的第一个server块作为默认server块
		#backlog=num:表示TCP中backlog队列的大小,默认-1,表示不予设置
		#rcvbuf=size: 设置监听句柄的SO_RCVBUF参数。
		#sndbuf=size: 设置监听句柄的SO_SNDBUF参数。
		#accept_filter: 设置accept过滤器, 只对FreeBSD操作系统有用
		#bind:绑定当前端口/地址,只有同时对一个端口监听多个地址时
才会生效。
		#ssl: 在当前监听的端口上建立的连接必须基于SSL协议。
		listen       8080;
 
		#主机名称:其后可以跟多个主机名称,开始处理一个HTTP请求时,nginx会取出header头中的Host,与每个server中的server_name进行匹配,以此决定到底由那一个server来处理这个请求。有可能一个Host与多个server块中的server_name都匹配,这时会根据匹配优先级来选择实际处理的server块。
	 	server_name  localhost;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        #location / {
        #    root   html;
        
        	##用来设置文件资源路径的
			#语法: alias path;
			#配置块: location
		#	alias usr/local/nginx/conf/;
        #    index  index.html index.htm;
        #}
        
        ##若请求的URI是/download/index/test.html, 那服务器就会返回服务器上optwebhtml、download/index/test.html文件的内容。
        #location /download/ {
		#	root optwebhtml;
		#}
		

 
		##location 语法: location [=|~|~*|^~|@]/uri/ { ... }
		#注意:location时有顺序的,当一个请求有可能匹配多个location时,实际上这个请求会被第一个location处理。
		location / {
			proxy_pass http://192.168.1.60;
   	 	}
   	 	
   	 	##按HTTP方法名限制用户请求
		#语法: limit_except method...{...}
		#配置块: location
		#方法名可取值包括: GET、HEAD、 POST、 PUT、 DELETE、 MKCOL、 COPY、 MOVE、 OPTIONS、 PROPFIND、PROPPATCH、 LOCK、 UNLOCK或者PATCH。 
		#limit_except GET {
		#	allow 192.168.1.0/32;
		#	deny all;
		#}
		#注意, 允许GET方法就意味着也允许HEAD方法。 因此, 上面这段代码表示的是禁止
GET方法和HEAD方法, 但其他HTTP方法是允许的。
		
		
		
 
		##根据HTTP返回码重定向页面
		#语法:error_page code[code...][=|=answer-code]uri|@named_location
		#配置块: http、 server、 location、 if
        #error_page  404              /404.html;
        error_page   500 502 503 504  /50x.html;
        
        ##是否允许递归使用error_page
		#语法: recursive_error_pages[on|off];
		#默认: recursive_error_pages off;
		#配置块: http、 server、 location
		
		##尝试按照顺序访问每一个path, 如果可以有效地读取, 就直接向用户返回这个path对应的文件结束请求, 否则继续向下访问。 如果所有的path都找不到有效的文件, 就重定向到最后的参数
uri上。 
		#因此最后一个path必须有url参数
		#语法: try_files path1[path2]uri;
		#配置块: server、 location
        
        location = /50x.html {
            root   html;
        }
        
        ##为了提高快速寻找到相应server name的能力, Nginx使用散列表来存储server name。
		#server_names_hash_bucket_size设置了每个散列桶占用的内存大小。
    	#语法: server_names_hash_bucket_size size;
		#默认: server_names_hash_bucket_size 32|64|128;
		#配置块: http、 server、 location
	
		##server_names_hash_max_size会影响散列表的冲突率。 server_names_hash_max_size越大,
消耗的内存就越多, 但散列key的冲突率则会降低, 检索速度也更快。
		#语法: server_names_hash_max_size size;
		#默认: server_names_hash_max_size 512;
		#配置块: http、 server、 location
	
		##重定向主机名称的处理
		#该配置需要配合server_name使用。 在使用on打开时, 表示在重定向请求时会使用
server_name里配置的第一个主机名代替原先请求中的Host头部, 而使用off关闭时, 表示在重
定向请求时使用请求本身的Host头部。
		#语法: server_name_in_redirect on|off;
		#默认: server_name_in_redirect on;
		#配置块: http、 server或者location
		
		##HTTP包体只存储到磁盘文件中
		#当值为非off时, 用户请求中的HTTP包体一律存储到磁盘文件中, 即使只有0字节也会存
储为文件。 当请求结束时, 如果配置为on, 则这个文件不会被删除(该配置一般用于调试、
定位问题) , 但如果配置为clean, 则会删除该文件。
		#语法: client_body_in_file_only on|clean|off;
		#默认: client_body_in_file_only off;
		#配置块: http、 server、 location
		
		##HTTP包体尽量写入到一个内存buffer中
		#用户请求中的HTTP包体一律存储到内存buffer中。 当然, 如果HTTP包体的大小超过了
下面client_body_buffer_size设置的值, 包体还是会写入到磁盘文件中。
		#语法: client_body_in_single_buffer on|off;
		#默认: client_body_in_single_buffer off;
		#配置块: http、 server、 location
		
		##存储HTTP头部的内存buffer大小
		#语法: client_header_buffer_size size;
		#默认: client_header_buffer_size 1k;
		#配置块: http、 server
		
		##存储超大HTTP头部的内存buffer大小
		#语法: large_client_header_buffers number size;
		#默认: large_client_header_buffers 48k;
		#配置块: http、 server
		
		##存储HTTP包体的内存大小
		#语法: client_body_buffer_siz size
		#默认: client_body_buffer_siz 8k/16k;
		#配置块:http、 server、 location
		
		##HTTP包体的临时存放目录
		#语法: client_body_temp_path dir-path[level1[level2[level3]]]
		#默认: client_body_temp_path client_body_temp;
		#配置块: http、 server、 location
		
		##指定内存池的初始大小
		#语法: connection_pool_size size;
		#默认: connection_pool_size 256;
		#配置块: http、 server
		
		##指定每个请求的内存池大小
		#语法: request_pool_size size;
		#默认: request_pool_size 4k;
		#配置块: http、 server
		
		##读取HTTP头部的超时时间
		#语法: client_header_timeout time(默认单位: 秒) ;
		#默认: client_header_timeout 60;
		#配置块: http、 server、 location
		
		##读取HTTP包体的超时时间
		#语法: client_body_timeout time(默认单位: 秒) ;
		#默认: client_body_timeout 60;
		#配置块: http、 server、 location
		
		##发送响应的超时时间
		#语法: send_timeout time;
		#默认: send_timeout 60;
		#配置块: http、 server、 location
		
		##连接超时后将通过向客户端发送RST包来直接重置连接
		#语法: reset_timeout_connection on|off;
		#默认: reset_timeout_connection off;
		#配置块: http、 server、 location
		
		##该配置控制Nginx关闭用户连接的方式。
		#语法: lingering_close off|on|always;
		#默认: lingering_close on;
		#配置块: http、 server、 location
		
		##lingering_close启用后, 这个配置项对于上传大文件很有用
		#语法: lingering_time time;
		#默认: lingering_time 30s;配置块: http、 server、 location
		
		##lingering_close生效后, 在关闭连接前, 会检测是否有用户发送的数据到达服务器, 如果
超过lingering_timeout时间后还没有数据可读, 就直接关闭连接; 否则, 必须在读取完连接缓
冲区上的数据并丢弃掉后才会关闭连接。
		#语法: lingering_timeout time;
		#默认: lingering_timeout 5s;
		#配置块: http、 server、 location
		
		##对某些浏览器禁用keepalive功能
		#语法: keepalive_disable[msie6|safari|none]...
		#默认: keepalive_disablemsie6 safari
		#配置块: http、 server、 location
		
		##keepalive超时时间
		#语法: keepalive_timeout time(默认单位: 秒) ;
		#默认: keepalive_timeout 75;
		#配置块: http、 server、 location
		
		##一个keepalive长连接上允许承载的请求最大数
		#语法: keepalive_requests n;
		#默认: keepalive_requests 100;
		#配置块: http、 server、 location
		
		##确定对keepalive连接是否使用TCP_NODELAY选项
		#语法: tcp_nodelay on|off;
		#默认: tcp_nodelay on;
		#配置块: http、 server、 location
		
		##在打开sendfile选项时, 确定是否开启FreeBSD系统上的TCP_NOPUSH或Linux系统上的
TCP_CORK功能。 打开tcp_nopush后, 将会在发送响应时把整个响应包头放到一个TCP包中
发送。
		#语法: tcp_nopush on|off;
		#默认: tcp_nopush off;
		#配置块: http、 server、 location
		
		##HTTP请求包体的最大值
		#语法: client_max_body_size size;
		#默认: client_max_body_size 1m;
		#配置块: http、 server、 location
		
		##对请求的限速
		#此配置是对客户端请求限制每秒传输的字节数。默认参数为0, 表示不限速。
		#语法: limit_rate speed;
		#默认: limit_rate 0;
		#配置块: http、 server、 location、 if
		
		##Nginx向客户端发送的响应长度超过limit_rate_after后才开始限速
		#语法: limit_rate_after time;
		#默认: limit_rate_after 1m;
		#配置块: http、 server、 location、 if
		
		##sendfile系统调用
		#语法: sendfile on|off;
		#默认: sendfile off;
		#配置块: http、 server、 location
		
		##AIO系统调用
        #语法: aio on|off;
        #默认: aio off;
        #配置块: http、 server、 location
        
        ##此配置项在FreeBSD和Linux系统上使用O_DIRECT选项去读取文件, 缓冲区大小为size,
通常对大文件的读取速度有优化作用。 
		#注意, 它与sendfile功能是互斥的。
        #语法: directio size|off;
        #默认: directio off;
        #配置块: http、 server、 location
		
		##指定以directio方式读取文件时的对齐方式
		#它与directio配合使用
        #语法: directio_alignment size;
        #默认: directio_alignment 512;
        #配置块: http、 server、 location
		
		##打开文件缓存
        #语法: open_file_cache max=N[inactive=time]|off;
        #默认: open_file_cache off;
        #配置块: http、 server、 location
        
        ##是否缓存打开文件错误的信息
		#语法: open_file_cache_errors on|off;
		#默认: open_file_cache_errors off;
		#配置块: http、 server、 location
		
		##不被淘汰的最小访问次数
		#它与open_file_cache中的inactive参数配合使用
		#语法: open_file_cache_min_uses number;
		#默认: open_file_cache_min_uses 1;
		#配置块: http、 server、 location
		
		##检验缓存中元素有效性的频率
		#默认为每60秒检查一次缓存中的元素是否仍有效
		#语法: open_file_cache_valid time;
		#默认: open_file_cache_valid 60s;
		#配置块: http、 server、 location
		
		##忽略不合法的HTTP头部
		#语法: ignore_invalid_headers on|off;
		#默认: ignore_invalid_headers on;
		#配置块: http、 server
		
		##HTTP头部是否允许下划线
		#语法: underscores_in_headers on|off;
		#默认: underscores_in_headers off;
		#配置块: http、 server
		
		##对If-Modified-Since头部的处理策略
        #语法: if_modified_since[off|exact|before];
        #默认: if_modified_since exact;
        #配置块: http、 server、 location
        
        ##文件未找到时是否记录到error日志
        #语法: log_not_found on|off;
        #默认: log_not_found on;
        #配置块: http、 server、 location
        
        ##是否合并相邻的“”
        #语法: merge_slashes on|off;
        #默认: merge_slashes on;
        #配置块: http、 server、 location
		
		##DNS解析地址
        #语法: resolver address...;
        #配置块: http、 server、 location
        
        ##DNS解析的超时时间
        #语法: resolver_timeout time;
        #默认: resolver_timeout 30s;
        #配置块: http、 server、 location
        
        ##返回错误页面时是否在Server中注明Nginx版本
        #语法: server_tokens on|off;
        #默认: server_tokens on;
        #配置块: http、 server、 location
        
--------------------负载均衡、反向代理----------------------------        
        
        ##upstream块,定义一个上游服务器集群
		#语法: upstream name{...}
		#配置块: http
		upstream backserver{
			##上游服务名可以为域名、ip端口
			#参数说明:
			- weight=1 权重;
			- max_fails=1与fail_time=10s配合使用,表示在10s内,上游服务器失败次数超过1次,则不可用
			- down:表示所在的上游服务器永久下线,只能使用ip_hash配置项时才能用
			- backup:在使用ip_hash配置项时它是无效的,指备份服务器,表示所有非备份服务器都失效,才会执行
			server 192.168.1.2:90;
			
			##ip_hash 有效地管理集群中相同的缓存信息
			#ip_hash与weight配置不可同时使用
			ip_hash;
		}
		
		##反向代理的基本配置
		#proxy_pass
		#语法: proxy_pass URL;
		#配置块: location、 if
		location / {
			proxy_pass http://backserver; #配置负载均衡
			#proxy_pass http://localhost:8080/test
			
			#注:默认情况,反向代理不会转发请求中的Host头部,如需,添加
			proxy_set_header Host $host;
			
			#proxy_method表示转发时的协议方法名。
            #语法: proxy_method method;
			#配置块: http、 server、 location
			proxy_method POST; #发来get请求,也会转化成POST
			
			#proxy_hide_header 指定HTTP头部字段哪些可以转发,默认不会转发
			#语法: proxy_hide_header the_header;
			#配置块: http、 server、 location
			proxy_hide_header Cache-Control;
			proxy_hide_header MicrosoftOfficeWebServer;
			
			#proxy_pass_header:将原来禁止转发的header设置为允许
转发
			#语法: proxy_pass_header the_header;
			#配置块: http、 server、 location
			proxy_pass_header X-Accel-Redirect;
			
			#proxy_pass_request_body:确定是否向上游服务器发送HTTP包体部分
			#语法: proxy_pass_request_body on|off;
			#默认: proxy_pass_request_body on;
			#配置块: http、 server、 location
			proxy_pass_request_body off;
			
			#proxy_pass_request_headers:确定是否转发HTTP头部
			#语法: proxy_pass_request_headers on|off;
			#默认: proxy_pass_request_headers on;
			#配置块: http、 server、 location
			
			#proxy_redirect:当上游服务器返回的响应是重定向或刷新请求(301或者302) 时,proxy_redirect可以重设HTTP头部的location或refresh字段。
			#语法: proxy_redirect[default|off|redirect replacement];
			#参数解释:off:使location或者refresh字段维持不变。
			#默认: proxy_redirect default;
			#配置块: http、 server、 location
			proxy_redirect off;
			
			#proxy_next_upstream:当一台上游服务转发请求出现错误时,继续换一台上游服务器转发请求
			#语法:proxy_next_upstream[error|timeout|invalid_header|http_500|http_502|http_503|http_504|http_404|off];
			#默认: proxy_next_upstream error timeout;
			#配置块: http、 server、 location
			proxy_next_upstream timeout;
		}
    } 
}

server_name与Host的匹配优先级

server_name与Host的匹配优先级 案例
首先选择所有字符串完全匹配的server_name 如:www.testwab.com
其次选择通配符在前面的server_name 如:*.testwab.com
其次选择通配符在后面的server_name 如:www.testwab.*
最后选择使用正在表达式才匹配的server_name 最后选择使用正在表达式才匹配的server_name

location的匹配规则

符号 解释
= 表示把URI作为字符串, 以便与参数中的uri做完全匹配。
~ 表示匹配URI时是字母大小写敏感的
~* 表示匹配URI时忽略字母大小写问题
^~ 表示匹配URI时只需要其前半部分与uri参数匹配即可
@ 仅用于Nginx服务内部请求之间的重定向, 带有@的location不直接处理用户请求

root和alias区别

如果有一个请求的URI是/conf/nginx.conf, 而用户实际想访问的文件
在usr/local/nginx/conf/nginx.conf。

alias:

alias在实际文件路径的映射过程中,已经将location后配置的/conf这部分去掉了

location conf {
	alias usr/local/nginx/conf/;
}

root:

而root没有去掉,这也是root可以放置到其他http、server等中,而alias只能放置location中的原因

location conf{
	root usr/local/nginx/;
}

alias还可以添加正则表达式:

location ~ ^/test/(\w+)\.(\w+)$ {
	alias usrlocal/nginx/$2/$1.$2;
}

请求访问/test/nginx.conf时,返回usr/local/nginx/conf/nginx.conf