1、全局优化

1.nginx用户和用户组

[root@c7-nginx-master-31 ~]# head -n 10 /apps/nginx/conf/nginx.conf
user  nobody;   #启动Nginx工作进程的用户和组
#user   nginx nginx;
worker_processes  1;

[root@c7-nginx-master-31 ~]# nginx -s reload

[root@c7-nginx-master-31 ~]# ps -aux | grep nginx
avahi       677  0.0  0.0  62268  2264 ?        Ss   14:44   0:00 avahi-daemon: running [c7-nginx-master-31.local]
root       1006  0.0  0.0  46264  2044 ?        Ss   14:44   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nobody     2128  0.0  0.0  48776  2116 ?        S    14:49   0:00 nginx: worker process
root       2130  0.0  0.0 112812   968 pts/0    S+   14:49   0:00 grep --color=auto nginx

[root@c7-nginx-master-31 ~]# head -n 10 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;    #启动Nginx工作进程的用户和组
worker_processes  1;

[root@c7-nginx-master-31 ~]# nginx -s reload
[root@c7-nginx-master-31 ~]# ps -aux | grep nginx
avahi       677  0.0  0.0  62268  2264 ?        Ss   14:44   0:00 avahi-daemon: running [c7-nginx-master-31.local]
root       1006  0.0  0.0  46264  2048 ?        Ss   14:44   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      2163  0.0  0.0  48776  2020 ?        S    14:50   0:00 nginx: worker process
root       2165  0.0  0.0 112812   968 pts/0    S+   14:50   0:00 grep --color=auto nginx

2.worker进程数量

[root@c7-nginx-master-31 ~]# head -n 10 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;
worker_processes  1;    #启动Nginx工作进程的数量,一般设为和CPU核心数相同

[root@c7-nginx-master-31 ~]# ps -aux | grep nginx
avahi       677  0.0  0.0  62268  2264 ?        Ss   14:44   0:00 avahi-daemon: running [c7-nginx-master-31.local]
root       1006  0.0  0.0  46264  2048 ?        Ss   14:44   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      2163  0.0  0.0  48776  2020 ?        S    14:50   0:00 nginx: worker process
root       2243  0.0  0.0 112812   968 pts/0    S+   14:51   0:00 grep --color=auto nginx

[root@c7-nginx-master-31 ~]# head -n 10 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;
worker_processes  4;    #启动Nginx工作进程的数量,一般设为和CPU核心数相同
#worker_processes   auto;

[root@c7-nginx-master-31 ~]# ps -aux | grep nginx
avahi       677  0.0  0.0  62268  2264 ?        Ss   14:44   0:00 avahi-daemon: running [c7-nginx-master-31.local]
root       1006  0.0  0.0  46264  2048 ?        Ss   14:44   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      2245  0.0  0.0  48776  2108 ?        S    14:52   0:00 nginx: worker process
nginx      2246  0.0  0.0  48776  2100 ?        S    14:52   0:00 nginx: worker process
nginx      2247  0.0  0.0  48776  2116 ?        S    14:52   0:00 nginx: worker process
nginx      2248  0.0  0.0  48776  2116 ?        S    14:52   0:00 nginx: worker process
root       2250  0.0  0.0 112812   964 pts/0    S+   14:52   0:00 grep --color=auto nginx

3.亲缘性绑定(worker进程绑定)

[root@c7-nginx-master-31 ~]# ps axo pid,cmd,psr |grep nginx
  1006 nginx: master process /apps   0
  2332 nginx: worker process         3
  2333 nginx: worker process         1
  2334 nginx: worker process         2
  2335 nginx: worker process         1
  2337 grep --color=auto nginx       0

[root@c7-nginx-master-31 ~]# head -n 10 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;
worker_processes  4;
worker_cpu_affinity 00000001 00000010 00000100 00001000;
#worker_cpu_affinity    auto;
#将Nginx工作进程绑定到指定的CPU核心,默认Nginx是不进行进程绑定的,绑定并不是意味着当前nginx进程独占以一核心CPU,但是可以保证此进程不会运行在其他核心上,这就极大减少了nginx的工作进程在不同的cpu核心上的来回跳转,减少了CPU对进程的资源分配与回收以及内存管理等,因此可以有效的提升nginx服务器的性能。

#00000001   代表0号cpu
#00000010   代表1号cpu
.....

[root@c7-nginx-master-31 ~]# nginx -s reload
[root@c7-nginx-master-31 ~]# ps axo pid,cmd,psr |grep nginx
  1006 nginx: master process /apps   0
  2373 nginx: worker process         0
  2374 nginx: worker process         1
  2375 nginx: worker process         2
  2376 nginx: worker process         3
  2378 grep --color=auto nginx       3

4.工作进程优先级

[root@c7-nginx-master-31 ~]# head -n 10 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;
worker_processes  4;
worker_cpu_affinity 00000001 00000010 00000100 00001000;
worker_priority -1; #工作进程优先级,-20~20(19)

[root@c7-nginx-master-31 ~]# ps axo pid,cmd,nice |grep nginx
  1006 nginx: master process /apps   0
  2429 nginx: worker process        -1
  2430 nginx: worker process        -1
  2431 nginx: worker process        -1
  2432 nginx: worker process        -1
  2434 grep --color=auto nginx       0

5.所有worker进程能打开的文件数量上限

[root@c7-nginx-master-31 ~]# head -n 10 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;
worker_processes  4;
worker_cpu_affinity 00000001 00000010 00000100 00001000;
worker_priority -1;
worker_rlimit_nofile 65536;#所有worker进程能打开的文件数量上限,包括:Nginx的所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接,另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制.最好与ulimit -n 或者limits.conf的值保持一致,默认不限制

[root@c7-nginx-master-31 ~]# ulimit -n 262140
[root@c7-nginx-master-31 ~]# cat /lib/systemd/system/nginx.service 
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
#指定pid文件的目录,默认在logs目录下,可选配置
PIDFile=/apps/nginx/run/nginx.pid
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
LimitNOFILE=262140

[Install]
WantedBy=multi-user.target

[root@c7-nginx-master-31 ~]# systemctl daemon-reload 
[root@c7-nginx-master-31 ~]# systemctl restart nginx

6.nginx前台运行

[root@c7-nginx-master-31 ~]# head -n 10 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;
worker_processes  4;
worker_cpu_affinity 00000001 00000010 00000100 00001000;
worker_priority -1;
worker_rlimit_nofile 262140;
daemon off;  #前台运行Nginx服务用于测试、或者以容器运行时,需要设为off


2、events块优化

1.设置单个工作进程的最大并发连接数

[root@c7-nginx-master-31 ~]# head -n 20 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;
....

events {
    worker_connections  65535;  #设置单个工作进程的最大并发连接数,默认1024,生产建议根据性能修改更大的值
}

....
[root@c7-nginx-master-31 ~]# nginx -s reload

2.使用epoll事件驱动

[root@c7-nginx-master-31 ~]# head -n 20 /apps/nginx/conf/nginx.conf
#user  nobody;
....

events {
    worker_connections  65535;
    use epoll;  #使用epoll事件驱动,Nginx支持众多的事件驱动,比如:select、poll、epoll,只能设置在events模块中设置。
}

....=
[root@c7-nginx-master-31 ~]# nginx -s reload

3.惊群

[root@c7-nginx-master-31 ~]# head -n 20 /apps/nginx/conf/nginx.conf
#user  nobody;
....

events {
    worker_connections  65535;
    use epoll;
    accept_mutex on;    #mutex互斥为on表示同一时刻一个请求轮流由worker进程处理,而防止被同时唤醒所有worker,避免多个睡眠进程被唤醒的设置,可以避免多个 worker 进程竞争同一连接而导致性能下降,也可以提高系统的稳定性,默认为off,新请求会唤醒所有worker进程,此过程也称为"惊群",在高并发的场景下多个worker进程可以各自同时接受多个新的连接请求,如果是多CPU和worker进程绑定,就可以提高吞吐量
}

....

[root@c7-nginx-master-31 ~]# nginx -s reload

4.同时接受多个新的网络连接

[root@c7-nginx-master-31 ~]# head -n 25 /apps/nginx/conf/nginx.conf
#user  nobody;
user    nginx nginx;
....

events {
    worker_connections  65535;
    use epoll;
    accept_mutex on;
    multi_accept on;    #on时Nginx服务器的每个工作进程可以同时接受多个新的网络连接,此指令默认为off,即默认为一个工作进程只能一次接受一个新的网络连接,打开后几个同时接受多个。建议设置为on
}
....

[root@c7-nginx-master-31 ~]# nginx -s reload


3、http块优化

1.sendfile高效传输

[root@c7-nginx-master-31 ~]# head -n 40 /apps/nginx/conf/nginx.conf
....
events {
    ....
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    ....

    sendfile        on;
    #tcp_nopush     on; #开启sendfile的情况下,合并请求后统一发送给客户端,必须开启sendfile,处理大量小数据包时推荐开启
    #tcp_nodelay   off; #开启keepalived模式下的连接是否启用TCP_NODELAY选项,为off时,延迟0.2s发送,默认On时,不延迟发送,立即发送用户响应报文。

....

[root@c7-nginx-master-31 ~]# nginx -s reload

2.长连接配置

[root@c7-nginx-master-31 ~]# head -n 40 /apps/nginx/conf/nginx.conf
....
events {
    ....
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    ....

    sendfile        on;
    keepalive_time 2h;          #限制对一个连接中请求处理的最长时间,到时间后续的再有新的请求会断开连接,默认1h
    keepalive_timeout  65 65;   #设置会话保持时间,第二个值为响应首部:keep-Alived:timeout=65,可以和第一个值不同
    keepalive_requests 2000;  #在一次长连接上所允许请求的资源的最大数量,默认为1000次

....

[root@c7-nginx-master-31 ~]# nginx -s reload

3.开启文件压缩

[root@c7-nginx-master-31 ~]# head -n 40 /apps/nginx/conf/nginx.conf
....
events {
    ....
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    ....

    gzip  on;
    gzip_comp_level  5;
    gzip_min_length  1k;
    gzip_http_version 1.1;
    gzip_buffers  16 8k;
    gzip_types  jpg png html;
    gzip_vary  on;
    gzip_static on;

....

[root@c7-nginx-master-31 ~]# nginx -s reload

4、server块优化

1.限速、限制连接数

limit_rate_after 100m;      #下载达到100MB数据后开始限速
limit_rate 100k;            #限速100k
limit_conn conn_zone 2;     #限制每个IP最大并发2个连接
limit_req zone=req_one burst=10 nodelay;
#第一个参数:zone=req_one 设置使用哪个配置区域来做限制,与上面limit_req_zone的name对应。
#第二个参数:burst=10,设置一个大小为10的缓冲区,当有大量请求过来时,超过了访问频次限制的请求可以先放到这个缓冲区内。
#第三个参数:nodelay,超过访问频次并且缓冲区也满了的时候,则会返回503,如果没有设置,则所有请求会等待排队。

#http块中
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
#第一个参数:$binary_remote_addr表示通过这个标识来做限制,限制同一客户端ip地址。
#第二个参数:zone=req_one:10m表示生成一个大小为10M,名为req_one的内存区域用来存储访问频次信息
#第三个参数:rate=1r/s表示允许相同标识的客户端的访问频次,此处限制的是每秒1次。

limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
#基于客户端IP限流,创建一个名为conn_zone且分配10M内存的zone

limit_conn zone number
#限制每个IP最大并发几个连接

[root@c7-nginx-master-31 ~]# head -n 40 /apps/nginx/conf/nginx.conf
....
events {
    ....
}

http {
    ....
    limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
    limit_conn_zone $binary_remote_addr zone=conn_zone:10m;

    server {
        listen       80;
        server_name  localhost;

    limit_rate_after 100m;
    limit_rate 100k;
    limit_conn conn_zone 2;
    limit_req zone=req_one burst=10 nodelay;    

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

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

[root@c7-nginx-master-31 nginx-1.22.1]# nginx -s reload

2.动静分离

#通过location去对不同的资源进行匹配优化

[root@c7-nginx-master-31 ~]# head -n 40 /apps/nginx/conf/nginx.conf
....
    server {
        listen       80;
        server_name  localhost;

    limit_rate_after 100m;
    limit_rate 100k;
    limit_conn conn_zone 2;
    limit_req zone=req_one burst=10 nodelay;    

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        location ~* \.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js|css)$ {
                root /data/photo;
                index index.html;
        }

        location ~* /app1 {
                ......;
        }
        location ~* /app2 {
                ......;
        }
        location ~ \.php$ {                 
                root           /data/nginx/wp;
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include       fastcgi_params;

}

3.HTTPS

ssl on | off;   
#为指定的虚拟主机配置是否启用ssl功能,此功能在1.15.0废弃,使用listen [ssl]替代
listen 443 ssl http2;

ssl_certificate /path/to/file;
#指向包含当前虚拟主机和CA的两个证书信息的文件,一般是crt文件

ssl_certificate_key /path/to/file;
#当前虚拟主机使用的私钥文件,一般是key文件

ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; 
#支持ssl协议版本,早期为ssl现在是TLS,默认为后三个,最新的浏览器已经不再支持TLS1.0和TLS1.1

ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
#配置ssl缓存
   off: #关闭缓存
    none:  #通知客户端支持ssl session cache,但实际不支持
    builtin[:size]:#使用OpenSSL内建缓存,为每worker进程私有,使用此内置缓存可能会导致内存碎片
    [shared:name:size]:#在各worker之间使用一个共享的缓存,需要定义一个缓存名称和缓存空间大小,1M可以存储4000个会话信息,多个虚拟主机可以使用相同的缓存名称
    ssl_session_timeout time; #客户端连接可以复用ssl session cache中缓存的有效时长,默认5分钟

[root@c7-nginx-master-31 ~]# tail -n 20 /apps/nginx/conf/nginx.conf
    server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      /data/www.jiutingqiu.com.pem;
        ssl_certificate_key  /data/www.jiutingqiu.com.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

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

}

4.反向代理

proxy_pass URL;
#用来设置将客户端请求转发给的后端服务器的主机,可以是主机名(将转发至后端服务做为主机头首部)、IP:port 方式
#说明: proxy_pass http://FQDN/ 中的FQDN决定转发至后端哪个虚拟主机,而与用户请求的URL无关
#如果转到后端的哪个服务器由用户请求决定,可以向后端服务转发请求的主机头实现
示例:
 location /web {
   index index.html;
   proxy_pass http://10.0.0.18:8080; #8080后面无uri,即无 / 符号,需要将location后面url 附加到proxy_pass指定的url后面,此行为类似于root

    #proxy_pass指定的uri不带斜线将访问的/web,等于访问后端服务器http://10.0.0.18:8080/web/index.html,即后端服务器配置的站点根目录下要有web目录才可以被访问
    # http://nginx/web/index.html ==> http://10.0.0.18:8080/web/index.html

   proxy_pass http://10.0.0.18:8080/;   #8080后面有uri,即有 / 符号,相当于置换,即访问/web时实际返回proxy_pass后面uri内容.此行为类似于alias 
    #proxy_pass指定的uri带斜线,等于访问后端服务器的http://10.0.0.18:8080/index.html 内容返回给客户端
 }  # http://nginx/web/index.html ==> http://10.0.0.18:8080

proxy_hide_header field;
#用于nginx作为反向代理的时候,在返回给客户端http响应时,隐藏后端服务器相应头部的信息,可以设置在http,server或location块

#示例: 隐藏后端服务器ETag首部字段
 location /web {
   index index.html;
   proxy_pass http://10.0.0.18:8080/; 
   proxy_hide_header ETag;
 }

proxy_pass_header field;
#默认nginx在响应报文中不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel等参数,如果要传递的话则要使用 proxy_pass_header field声明将后端服务器返回的值传递给客户端
#field 首部字段大小不敏感

#示例:透传后端服务器的Server和Date首部给客户端,同时不再响应报中显示前端服务器的Server字段
proxy_pass_header Server;
proxy_pass_header Date;

proxy_pass_request_body on | off; 
#是否向后端服务器发送HTTP实体部分,可以设置在http,server或location块,默认即为开启

proxy_pass_request_headers on | off; 
#是否将客户端的请求头部转发给后端服务器,可以设置在http,server或location块,默认即为开启

proxy_set_header; 
#可更改或添加客户端的请求头部信息内容并转发至后端服务器,比如在后端服务器想要获取客户端的真实IP的时候,就要更改每一个报文的头部

#示例: 
#proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
$proxy_add_x_forwarded_for
the “X-Forwarded-For” client request header field with the $remote_addr variable appended to it, separated by a comma. If the “X-Forwarded-For” field is not present in the client request header, the $proxy_add_x_forwarded_for variable is equal to the $remote_addr variable.

proxy_set_header X-Real-IP  $remote_addr;  
#添加HOST到报文头部,如果客户端为NAT上网那么其值为客户端的共用的公网IP地址,常用于在日之中记录客户端的真实IP地址。
#在后端httpd服务器修改配置,添加日志记录X-Forwarded-For字段LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Real-IP}i\"" combined 

proxy_connect_timeout time;
#配置nginx服务器与后端服务器尝试建立连接的超时时间,默认为60秒,用法如下:
proxy_connect_timeout 6s; 
#60s为自定义nginx与后端服务器建立连接的超时时间,超时会返回客户端504响应码

proxy_read_timeout time;
#配置nginx服务器向后端服务器或服务器组发起read请求后,等待的超时时间,默认60s

proxy_send_timeout time; 
#配置nginx项后端服务器或服务器组发起write请求后,等待的超时 时间,默认60s

proxy_http_version 1.0; 
#用于设置nginx提供代理服务的HTTP协议的版本,默认http 1.0,建议修改1.1支持长连接
#注意:需要配合实现proxy_set_header Connection "" 实现长连接,否则在高并发时,可能会造成server端出现大量TIME_WAIT

proxy_ignore_client_abort off; 
#当客户端网络中断请求时,nginx服务器中断其对后端服务器的请求。即如果此项设置为on开启,则服务器会忽略客户端中断并一直等着代理服务执行返回,如果设置为off,则客户端中断后Nginx也会中断客户端请求并立即记录499日志,默认为off

proxy_headers_hash_bucket_size 128;
#当配置了 proxy_hide_header和proxy_set_header的时候,用于设置nginx保存HTTP报文头的hash表的上限

proxy_headers_hash_max_size 512; 
#设置proxy_headers_hash_bucket_size的最大可用空间

server_names_hash_bucket_size 512; 
#server_names的hash表申请空间大小

server_names_hash_max_size  512; 
#设置服务器名称hash表的上限大小

proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504;
#当一台后端朋务器出错,超时,无效首部,500等时,切换至下一个后端服务器提供服务
实例:
[root@c7-nginx-master-31 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
 listen 80;
 server_name www.jiutingqiu.com;
 location / {
     proxy_pass http://10.0.0.18/; # http://10.0.0.18/ 最后的 / 可加或不加
     proxy_set_header Host  $http_host; #转发主机头至后端服务器
     proxy_connect_timeout 10s;
 }
}

5.反向代理缓存

proxy_cache_path;
#定义可用于proxy功能的缓存;Context:http 
proxy_cache_path path [levels=levels] [use_temp_path=on|off] 
keys_zone=zone_name:size [inactive=time] [max_size=size] [manager_files=number] 
[manager_sleep=time] [manager_threshold=time] [loader_files=number] 
[loader_sleep=time] [loader_threshold=time] [purger=on|off] 
[purger_files=number] [purger_sleep=time] [purger_threshold=time];

#示例:在http配置定义缓存信息
proxy_cache_path /var/cache/nginx/proxy_cache #定义缓存保存路径,proxy_cache会自动创建
   levels=1:2:2 #定义缓存目录结构层次,1:2:2可以生成2^4x2^8x2^8=2^20=1048576个目录
   keys_zone=proxycache:20m #指内存中缓存的大小,主要用于存放key和metadata(如:使用次数),一般1M可存放8000个左右的key
   inactive=120s  #缓存有效时间  
   max_size=10g; #最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值

proxy_cache zone_name | off; 默认off
#指明调用的缓存,或关闭缓存机制;Context:http, server, location
#zone_name 表示缓存的名称.需要由proxy_cache_path事先定义

proxy_cache_key string;
#缓存中用于“键”的内容,默认值:proxy_cache_key $scheme$proxy_host$request_uri; 

proxy_cache_valid  time;
#定义对特定响应码的响应内容的缓存时长,定义在http{...}中
 示例:
 proxy_cache_valid 200 302 10m;
 proxy_cache_valid 404 1m;

#调用缓存功能,需要定义在相应的配置段,如server{...};或者location等
proxy_cache proxycache;
proxy_cache_key $request_uri; #对指定的数据进行MD5的运算做为缓存的key
proxy_cache_valid 200 302 301 10m; #指定的状态码返回的数据缓存多长时间
proxy_cache_valid any 1m;   #除指定的状态码返回的数据以外的缓存多长时间,必须设置,否则不会缓存

proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | 
http_502 | http_503 | http_504 | http_403 | http_404 | off ; #默认是off
#在被代理的后端服务器出现哪种情况下,可直接使用过期的缓存响应客户端
#示例
proxy_cache_use_stale error http_502 http_503;

proxy_cache_methods GET | HEAD | POST ...;
#对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存
[root@c7-nginx-master-31 ~]# cat /apps/nginx/conf/nginx.conf
......

http {
......

    proxy_cache_path /data/nginx/proxycache   levels=1:1:1  keys_zone=proxycache:20m inactive=120s  max_size=1g;

    server {
        listen       80;
        server_name  localhost;

        ......

        location /test {
            root   html;
            index  index.html index.htm;
        proxy_pass http://172.29.7.32:80;
            proxy_cache proxycache;
            proxy_cache_key $request_uri;
            proxy_cache_valid 200 302 301 10m;
            proxy_cache_valid any 5m;  #必须指定哪些响应码的缓存
            proxy_set_header Host  $http_host; #转发主机头至后端服务器
        }

.....

}

[root@c7-nginx-master-31 ~]# mkdir -pv /data/nginx/proxycache
[root@c7-nginx-master-31 ~]# systemctl restart nginx
[root@c7-nginx-master-31 ~]# ll /data/nginx/proxycache/
total 0
drwx------. 3 nginx nginx 15 Feb 13 16:58 9
drwx------. 3 nginx nginx 15 Feb 13 16:58 f

6.负载均衡

server address [parameters];
#配置一个后端web服务器,配置在upstream内,至少要有一个server服务器配置

#server支持的parameters如下:
weight=number #设置权重,默认为1,实现类似于LVS中的WRR,WLC等
max_conns=number  #给当前后端server设置最大活动链接数,默认为0表示没有限制
max_fails=number  #后端服务器的下线条件,当客户端访问时,对本次调度选中的后端服务器连续进行检测多少次,如果都失败就标记为不可用,默认为1次,当客户端访问时,才会利用TCP触发对探测后端服务器健康性检查,而非周期性的探测
fail_timeout=time #后端服务器的上线条件,对已经检测到处于不可用的后端服务器,每隔此时间间隔再次进行检测是否恢复可用,如果发现可用,则将后端服务器参与调度,默认为10秒
backup  #设置为备份服务器,当所有后端服务器不可用时,才会启用此备用服务器,和ip_hash指令冲突,不能同时使用
        #注意:此指令指向地址是自已的虚拟主机server,可能会造成死循环而出现500错误,应该指向另一个虚拟主机的server
down    #标记为down状态,可以平滑下线后端服务器,新用户不再调度到此主机,正在访问的旧用户不受影响
实例
[root@c7-nginx-master-31 ~]# cat /apps/nginx/conf/nginx.conf
#user  nobody;
....

http {
....

    upstream webserver {
    server 172.29.7.32:80 weight=1 fail_timeout=5s max_fails=3; #后端服务器状态监测
    server 172.29.7.33:80 weight=1 fail_timeout=5s max_fails=3;
    }

    server {
        listen       80;
        server_name  localhost;

    limit_rate_after 100m;
    limit_rate 100k;
    limit_conn conn_zone 2;
    limit_req zone=req_one burst=10 nodelay;    

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

    location /web {
        index index.html;
        proxy_pass http://webserver/;
        proxy_set_header Host  $http_host; #转发主机头至后端服务器
            proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504; #选择需要的

    }

....
}

7.会话保持

ip_hash;
#源地址hash调度方法,基于的客户端的remote_addr(源地址IPv4的前24位或整个IPv6地址)做hash计算,以实现会话保持,注意:如果是局域网可能会导致调度到同一台主机
#hash $remote_addr 则是对全部32bit的IPv4进行hash计算
#注意:和backup指令冲突,不能同时使用

least_conn; 
#最少连接调度算法,优先将客户端请求调度到当前连接最少的后端服务器,相当于LVS中的WLC

hash KEY [consistent];
#基于指定请求报文中首部字段或者URI等key做hash计算,使用consistent参数,将使用ketama一致性hash算法,适用于后端是Cache服务器(如varnish)时使用,consistent定义使用一致性hash运算,一致性hash基于取模运算

#示例
hash $request_uri consistent; #基于用户请求的uri做hash,可以实现调度到后端缓存服务器功能
hash $remote_addr consistent; #则是对全部32bit的IPv4进行一致性hash计算
hash $cookie_sessionid        #基于cookie中的sessionid这个key进行hash调度,实现会话绑定
实例
[root@c7-nginx-master-31 ~]# cat /apps/nginx/conf/nginx.conf
#user  nobody;
....

http {
....

    upstream webserver {
        #ip_hash;       #源地址hash调度方法
        #least_conn;    #最少连接调度算法
        #hash $request_uri consistent;  ##基于用户请求的uri做hash
        #hash $cookie_sessionid #基于cookie中的sessionid这个key进行hash调度,实现会话绑定
        #cooki不一定非的是sessionid,也可以是自定义的
        server 172.29.7.32:80 weight=1 fail_timeout=5s max_fails=3; #后端服务器状态监测
        server 172.29.7.33:80 weight=1 fail_timeout=5s max_fails=3;
    }

    server {
        listen       80;
        server_name  localhost;

    limit_rate_after 100m;
    limit_rate 100k;
    limit_conn conn_zone 2;
    limit_req zone=req_one burst=10 nodelay;    

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

    location /web {
        index index.html;
        proxy_pass http://webserver/;
        proxy_set_header Host  $http_host; #转发主机头至后端服务器
            proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504;

    }

....
}

8.HTTP跳转HTTPS

location / {
   root /data/nginx/html;
   if ( $scheme = http ) {
         rewrite ^/(.*)$ https://www.jiutingqiu.com/$1 redirect;                     

   }

Related Post

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注