nginx优化、负载均衡、rewrite

nginx优化

# 普通用户启动 (useradd nginx -s /sbin/nologin -M)
user nginx;

# 配置nginx worker进程个数
#worker_processes 8;
#worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
#worker_cpu_affinity 0001 0010 0100 1000 0001 0010 1000 0001 0010 0100 1000;

worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;

#worker_processes 2;
#worker_cpu_affinity 0101 1010;

# 配置日志存放路径
access_log  logs/access.log  warn;
error_log   logs/error.log  main;
pid logs/nginx.pid;

# nginx事件处理模型优化
events {
    worker_connections 65535; # 当个进程允许的客户端最大连接数
    use epoll;
    }

# 配置nginx worker进程最大打开文件数
work_rlimit_nofile 65535;

http {
    
    # 隐藏版本号
    server_tokens off;
    
    # 设置日志格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
        
    # 开启高效文件传输模式
    include mime.types;                         # 媒体类型
    default_type    application/octet-stream;   # 默认媒体类型
    charset  utf-8;                             # 默认字符集
    sendfile    on;
    tcp_nopush  on;                             # 只有在sendfile开启模式下有效
    
    # 设置连接超时时间
    keepalive_timeout  65;      # 设置客户端连接保持会话的超时时间,超过则服务器会关闭该连接
    tcp_nodelay on;             # 打开tcp_nodelay,在包含了keepalive参数才有效果
    client_header_timout 15;    # 设置客户端请求有超时时间,该时间内客户端未发送数据,nginx将返回‘Request time out(408)’错误
    client_body_timeout 15;    # 设置客户端请求体超时时间,同上
    send_timeout 15;            # 设置相应客户端的超时时间,超时nginx将会关闭连接
    
    # 上传文件大小设置(动态引用)
    client_max_body_size 10m;
    
    # 数据包头部缓存大小
    client_header_buffer_size    1k;        #默认请求包头信息的缓存    
    large_client_header_buffers  4 4k;      #大请求包头部信息的缓存个数与容量
   
    # 压缩处理
    gzip on;                           #开启压缩
    gzip_min_length 1k;              #小文件不压缩
    gzip_comp_level 4;                 #压缩比率
    gzip_buffers 4 16k;                #压缩缓冲区大小,申请4个单位为16K的内存作为亚索结果流缓存    
    gzip_http_version 1.1              # 默认压缩版本
    #对特定文件压缩,类型参考mime.types
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_vary on;
    gzip_disable "MSIE[1-6]."; 
    
    # 设置fastcgi
    fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2
                keys_zone=TEST:10m
                inactive=5m;       # 为FastCGI缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间
    fastcgi_connect_timeout 300;   # 指定连接到后端FastCGI的超时时间
    fastcgi_send_timeout 300;      # 向FastCGI传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI传送请求的超时时间   
    fastcgi_read_timeout 300;      # 接收FastCGI应答的超时时间,这个值是指已经完成两次握手后接收FastCGI应答的超时时间    
    fastcgi_buffer_size 16k;       # 缓冲区大小 
    fastcgi_buffers 16 16k;
    fastcgi_busy_buffers_size 16k;      
    fastcgi_temp_file_write_size 16k;   # 在写入fastcgi_temp_path时将用多大的数据块,默认值是fastcgi_buffers的两倍  
    fastcgi_cache TEST;                 # 开启FastCGI缓存并且为其制定一个名称
    fastcgi_cache_valid 200 302 1h;
    fastcgi_cache_valid 301 1d;
    fastcgi_cache_valid any 1m;         # 为指定的应答代码指定缓存时间,上例中将200,302应答缓存一小时,301应答缓存1天,其他为1分钟
    fastcgi_cache_min_uses 1;           # 5分钟内某文件1次也没有被使用,那么这个文件将被移除
    fastcgi_cache_use_stale error timeout invalid_header http_500;
    
    # 内存缓存
    open_file_cache   max=2000  inactive=20s; #设置服务器最大缓存文件数量,关闭20秒内无请求的文件
    open_file_cache_valid    60s;             #文件句柄的有效时间是60秒,60秒后过期     
    open_file_cache_min_uses 5;               #只有访问次数超过5次会被缓存  
    open_file_cache_errors   off;
    }

# 引入子配置文件 include vhost
/*.conf # 限制客户端请求的http方法 #if ($request_method !~ ^(GET|HEAD|POST)$ ) { # return 501; #} # 防止N多爬虫代理访问网站 if ($http_user_agent ~* "qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot") { return 403; } } location ~* .(jpg|jpeg|gif|png|css|js|ico|xml)$ { expires 30d; #定义客户端缓存时间为30天 }

nginx的upstream的负载均衡 目前支持的几种方式

1.轮询(默认)----每个请求按时间顺序逐一分配到不同的后端服务器(down掉的服务器会被自动剔除)

upstream bakend {
    server 192.168.1.1;
    server 192.168.1.2;
}

2.weight----指定轮询几率,weight与访问成正比,可将性能好的服务器配置较大的weight(down掉的服务器会自动剔除)

upstream bakend {
    server 192.168.1.1 weight=1;
    server 192.168.1.2 weight=2;
}

3.ip_hash----按请求的ip hash结果分配,这样每个访客固定访问一个后端服务器,可解决session共享问题(down掉的服务器要手工处理)

upstream real_server{
    ip_hash;
    server 192.168.1.1:8080 max_fails=3 fail_timeout=15s;
    server 192.168.1.2:8080 max_fails=3 fail_timeout=15s;
}

4.fire(第3方插件)---按后端服务器的响应时间来分配请求,响应时间短的优先分配

upstream real_server{
    server 192.168.1.1:8080;
    server 192.168.1.2:8080;
    fair;
}

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

upstream real_server{
    server 192.168.1.1:8080;
    server 192.168.1.2:8080;
    hash $request_uri;
    hash_method crc32;
}

示例

client_body_buffer_size    128k;                        //允许客户端请求缓存大小
client_max_body_size    100m;                            //允许请求的最大文件容量
large-client_header_buffers    4    8k;                 //
proxy_buffering    on;                                   //开启代理缓冲功能
proxy_buffer_size    8k;                                 //第一部分响应数据的缓存大小
proxy_buffers    8    128k;                              //响应数据的缓存个数和容量
proxy_cache_path    /usr/local/nginx/cache    levels=1:2    keys_zone=one:100m    inactive=1d    max_size=2G;   

//设置缓存目录,levels设置缓存个数,keys_zone定义缓存名字和容量,inactive定义缓存存活时间,max_size定义硬盘的缓存容量
proxy_connect_timeout    60s;            //与后端服务器建立TCP连接握手超时时间
upstream servers {

//ip_hash;ip_hash确保相同客户端ip使用相同的后端服务器,不适用就默认轮询
server    192.168.1.3:80    max_fails=3    fail_timeout=30s    weight=2;
server    192.168.1.4:80    max_fails=3    fail_timeout=30s    weight=2;
server    192.168.1.5:80    max_fails=3    fail_timeout=30s    weight=2;
}

server {
    listen    80;
    server_name    web.test.com;
    access_log    logs/host.access.log    main;
#    location ~* .(mp3|mp4)$ {                  //匹配URL以MP3或者MP4结尾的请求
#        proxy_pass http://localhost:8080        //转发到本机8080端口
#   }

#    location / {                                    //匹配任意URL
#        proxy_pass http://localhost:8080            //转发到本机8080端口
#        proxy_set_header    X-Forwarded-For    $remote_addr    //保留用户真实IP
#   } 
    
    location / {
        proxy_pass http://servers;
        proxy_cache one;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}

nginx的rewrite规则

1.根据浏览器标识,访问资源重定向到指定文件目录(以下为IE)

if ($http_user_agent ~ MSIE ) {
   rewrite ^(.*)$ /msie/$1 break;
}

2.将移动客户端的请求重定向到其他服务器

if    ($http_user_agent ~* '(iphone|ipod)' { 
    rewrite ^.+    http://mobile.site.com$uri;
}

3.用户使用POST方式请求数据时候,返回405:

if ($request_method = POST ) {
   return 405;
}

4.访问xxxx时重定向到xxxx目录

location /xxxx {
     rewrite ^/xxxx/.*$ /xxxx permanent;
}

Nginx Rewrite的基本标记

last       基本上都用这个Flag。相当于Apache里的[L]标记,表示完成rewrite,不再匹配后面的规则
break      中止 Rewirte,不再继续匹配
redirect   返回临时重定向的HTTP状态302
permanent  返回永久重定向的HTTP状态301。原有的url支持正则,重写的url不支持正则

正则表达式匹配

* ~       区分大小写匹配
* ~*      不区分大小写匹配
* !~和!~*   区分大小写不匹配及不区分大小写不匹配

文件及目录匹配

* -f 和!-f    用来判断是否存在文件
* -d 和!-d    用来判断是否存在目录
* -e 和!-e    用来判断是否存在文件或目录
* -x 和!-x    用来判断文件是否可执行

Nginx的一些可用的全局变量,可用做条件判断:

$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query_string
$scheme
$server_protocol
$server_addr
$server_name
$server_port
$uri

if指令

1)一个变量名;false如果这个变量是空字符串或者以0开始的字符串;
2)使用= ,!= 比较的一个变量和字符串
3)是用~, ~*与正则表达式匹配的变量,如果这个正则表达式中包含},;则整个表达式需要用" 或' 包围
4)使用-f ,!-f 检查一个文件是否存在
5)使用-d, !-d 检查一个目录是否存在
6)使用-e ,!-e 检查一个文件、目录、符号链接是否存在
7)使用-x , !-x 检查一个文件是否可执行
if ($http_user_agent ~ MSIE) {
     rewrite ^(.*)$ /msie/$1 break;
 }

 if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
     set $id $1;
 }

 if ($request_method = POST) {
     return 405;
 }

 if ($slow) {
     limit_rate 10k;
 }

 if ($invalid_referer) {
     return 403;
 }

location ~.(js|css|jpg|jpeg|gif|png|swf)$ {
  if (-f $request_filename) {
     root /data/www/wwwroot/bbs;
     expires 1d;
     break;
  }
}

ocation ^/(images|JavaScript|js|css|flash|media|static)/ {
   root /data/www/wwwroot/down;
   expires 30d;
}

原文地址:https://www.cnblogs.com/ray-mmss/p/11162920.html