nginx配置详解及如何解决跨域、GEO白名单、限速、限流(防止DDOS攻击)

本配置中有些功能是在window下测试,而由于windows下nginx好像对有些功能有限制,所以只做了名词功能标注,功能注释了

##定义nginx运行的用户各用户组
#user  nobody;
##nginx进程数,建议设置与cpu核心数一致
worker_processes  1;
#windows下好像不支持
#worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

##全局错误日志定义类型[ debug | info | notice | warn | error | crit ]
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

##一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)
##与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。
#worker_rlimit_nofile 65535;

##进程文件
#pid        logs/nginx.pid;

##工作模式与连接数上限
events {
    ##参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; 
    ##epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
    ##use epoll; 
    
    worker_connections  1024;
}


##设置http服务器
http { 

    ##文件扩展名与文件类型映射表
    include       mime.types;

    ##默认文件类型
    default_type  application/octet-stream;

    ##默认编码
    #charset utf-8;
    

    ##上传文件大小限制   建议打开
    client_header_buffer_size 32K;
    
    
    ##设定请求缓存 建议打开
    large_client_header_buffers 4 64K;
    
    
    ##最大缓存
    client_max_body_size 20M;
    
    client_header_timeout        20;
    
    ##服务器名字的hash表大小
    ##server_names_hash_bucket_size  64;



    proxy_set_header Host $host;

    ##日志格式设定
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    log_format main '$remote_addr "$http_x_real_ip" - $remote_user [$time_local] "$request" $http_host '
                    '$status $body_bytes_sent "$http_referer" '
		    '"$http_user_agent" "$http_x_forwarded_for"';

    ##访问日志
    #access_log  logs/access.log  main;


    ##开启高效文件传输模式sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,
    ##如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。
    ##注意:如果图片显示不正常把这个改成off。
    sendfile        on;

    ##防止网络阻塞  建议打开
    #tcp_nopush     on;

    ##防止网络阻塞  建议打开
    tcp_nodelay   on;

    ##长链接超时时间,单位是秒,为0,无超时 
    keepalive_timeout  65;

    ##gzip模块设置
    ##开启gzip压缩输出  建议打开
    gzip  on;
    
    ##最小压缩文件大小  建议打开
    gzip_min_length  1k;
    
    
    ##压缩缓冲区 建议打开
    gzip_buffers  4  16k;
    
    ##压缩版本(默认1.1,前端如果squid2.5请使用1.0) 建议打开
    gzip_http_version 1.0;
    
    ##压缩等级 建议打开
    gzip_comp_level 2; 
    
    ##压缩类型,默认就已经包含了textxml,默认不用写,写上去也没有问题,会有一个warn 建议打开
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;
    
 

    ##放第一个server段的前面
    ##开启SSI模块后静态页面就支持<!--#include file="header.html"-->
    #开启ssi
    ssi on;

    #设置ssi解析出错静默模式
    ssi_silent_errors on;

    #支持shtml文件,此处注释了,默认支持html文件
    ssi_types text/shtml;

    ##反向代理缓存Proxy Cache配置
    ##主要是用于对后端内容资源服务器进行缓存与FastCGI功能基本上一样。
  
    ##用于设置缓存文件的存放路径
    ## 注:proxy_temp_path和proxy_cache_path指定的路径必须在同一分区
    proxy_temp_path D:/nginx/cache/temp;
    
    proxy_cache_path D:/nginx/cache/proxy_cache_image levels=1:2 keys_zone=cache_image:600m inactive=1d max_size=2g;
    #proxy_cache_path  D:/nginx/cache/proxy_cache_image levels=1:2 keys_zone=cache_image:3000m inactive=1d max_size=10g;
    
    #proxy_cache_path配置
    #keys_zone=infcache:600m 表示这个zone名称为cache_image(Web缓存区名称),分配的内存大小为600MB
    #/opt/cache/nginx/cache 表示cache这个zone的文件要存放的目录
    #levels=1:2 表示缓存目录的第一级目录是1个字符,第二级目录是2个字符,即/data/ngx_cache/cache1/a/1b这种形式
    #inactive=1d 表示这个zone中的缓存文件如果在1天内都没有被访问,那么文件会被cache manager进程删除掉
    #max_size=10g 表示这个zone的硬盘容量为10GB

    ##使用Web缓存区cache_image
    proxy_cache cache_image;

    ##对不同的HTTP状态码缓存设置不同的缓存时间
    proxy_cache_valid 200 304 12h;
    proxy_cache_valid 301 302 1m;
    proxy_cache_valid any 1m;

    ##设置Web缓存的Key值,Nginx根据key值MD5哈希存储缓存,这里根据“域名、URL、参数”组合成Key。
    proxy_cache_key $host$uri$is_args$args;

    ##跟后端服务器连接的超时时间_发起握手等候响应超时时间
    proxy_connect_timeout 30;

    ##连接成功后_等候后端服务器响应时间_其实已经进入后端的排队等候处理
    proxy_read_timeout 60;

    ##后端服务器数据回传时间_就是在规定时间之内后端服务器必须传完所有的数据
    proxy_send_timeout 20;

    ##代理请求缓存区_这个缓存区间会保存用户的头信息以供Nginx进行规则处理_一般只要能保存下头信息即可
    proxy_buffer_size 96k;

    ##同上,告诉Nginx保存单个用的几个buffer最大用多大空间
    proxy_buffers 8 256k;

    ##如果系统很忙的时候可以申请更大的proxy_buffers 官方推荐*2
    proxy_busy_buffers_size 512k;

    ##proxy缓存临时文件的大小
    proxy_temp_file_write_size 512k;

    ##FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。
    ##主要用于对PHP、JSP、ASP这种动态程序进行缓存
    ##用于设置缓存文件的存放路径
    ## 注:fastcgi_temp_path和fastcgi_cache_path指定的路径必须在同一分区
    fastcgi_temp_path D:/nginx/cache/temp/fastcgi_temp;
    
    fastcgi_cache_path D:/nginx/cache/fast_cgi_cache levels=1:2 keys_zone=cache_one:600m inactive=1d max_size=2g;
     
    #fastcgi_cache_path配置
    #keys_zone=infcache:600m 表示这个zone名称为cache_image(Web缓存区名称),分配的内存大小为600MB
    #/opt/cache/nginx/cache 表示cache这个zone的文件要存放的目录
    #levels=1:2 表示缓存目录的第一级目录是1个字符,第二级目录是2个字符,即/data/ngx_cache/cache1/a/1b这种形式
    #inactive=1d 表示这个zone中的缓存文件如果在1天内都没有被访问,那么文件会被cache manager进程删除掉
    #max_size=10g 表示这个zone的硬盘容量为10GB
 
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    
    
    #设定负载均衡的服务器列表
    upstream mysvr {
        #weigth参数表示权值,权值越高被分配到的几率越大
        #本机上的Squid开启3128端口
        server 127.0.0.1:3128 weight=5;
        server 127.0.0.1:80   weight=1;
        server localhost:80   weight=6;
    }

    ##限速、限流、防DDOS攻击等配置
    limit_conn_log_level error;

    limit_conn_status 503;

    #开启限制连接数
    limit_conn_zone $binary_remote_addr zone=perip:10m;

    limit_conn_zone $server_name zone=perserver:10m;
    
    
    ##开启限制请求数
    #其中$binary_remote_addr有时需要根据自己已有的log_format变量配置进行替换
    #Zone=one或allips 表示设置了名为“one”或“allips”的存储区,大小为10兆字节
    #rate=10r/s 的意思是允许1秒钟不超过10个请求
    #定义一个名为allips的limit_req_zone用来存储session,大小是10M内存,
    #以$binary_remote_addr 为key,限制平均每秒的请求为20个,
    #1M能存储16000个状态,rete的值必须为整数,
    #如果限制两秒钟一个请求,可以设置成30r/m
    limit_req_zone $binary_remote_addr zone=allips:100m   rate=10r/s;   

    #限制连接数,请求数的白名单
    #白名单配置可用于对合作客户,搜索引擎等请求过滤限制
    #geo 则主要定义白名单配置,变量为 $white_ip,{ }内则定义参数及具体的值。
    #最下面使用 limit_req_whitelist 应用所配置的白名单,其中geo_var_name表示geo模块设置的变量名;
    #而geo_var_value表示geo模块设置的变量值;所有白名单内的IP不受任何限制。
    geo $white_ip {
        default 1 ;
        127.0.0.1/32 0;
        #192.168.50.0/19 0;
    }
     
    #使用map指令映射将白名单列表中客户端请求ip为空串
    map $white_ip $limit{
        1 $binary_remote_addr ;
        0 "";
    }
    #配置请求限制内容
    limit_conn_zone $limit zone=conn:10m;
    limit_req_zone $limit zone=allipsa:10m rate=20r/s;

    #limit_req_whitelist geo_var_name=white_ip geo_var_value=1;



    #如果想仅限制指定的请求,如:只限制Post请求,则
    #定义白名单列表
    geo $whiteiplist {
        default 1 ;
        127.0.0.1/32 0;
        #192.168.50.0/19 0;
    }
    map $whiteiplist $limitips{
        1 $binary_remote_addr;
        0 "";
    }
 
    #基于白名单列表,定义指定方法请求限制
    map $request_method $limit_post {
        default "";
        # POST $binary_remote_addr;
        POST $limitips;
    }
 
    #对请求进行引用
    limit_req_zone $limit_post zone=reqlimit:20m rate=10r/s;




    ##引入外置配置文件
    include "/nginx/conf/conf.d/minitor_nginx_status.conf";
    include "/nginx/conf/conf.d/wechat-test.yimidida.com";


    ##虚拟主机配置
    server {
        ##监听端口
        listen       80;

	##域名可以有多个,用空格隔开
        server_name  mysvr;


        ##开启目录列表访问,合适下载服务器,默认关闭
	##解决目录403 Forbidden
	autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;

        charset utf-8;
        #access_log  logs/access.log;

	root "D:/Workspaces/front/";

	 
	#表示最大并发连接数100,见上面,perip作用的key 是 $binary_remote_addr,表示限制单个IP同时最多能持有10个连接。
	limit_conn perip 10;

        #作用的key是 $server_name,表示虚拟主机(server) 同时能处理并发连接的总数。
        #表示该服务提供的总连接数不得超过1000,超过请求的会被拒绝
	#需要注意的是:只有当 request header 被后端server处理后,这个连接才进行计数。
        limit_conn perserver 1000;

        
	#表示最大延迟请求数量不大于5。  
	#如果太过多的请求被限制延迟是不需要的 ,这时需要使用nodelay参数,服务器会立刻返回503状态码。
	#限制每ip每秒不超过20个请求,漏桶数burst为5
        #brust的意思就是,如果第1秒、2,3,4秒请求为19个,
        #第5秒的请求为25个是被允许的。
        #但是如果你第1秒就25个请求,第2秒超过20的请求返回503错误。
        #nodelay,如果不设置该选项,严格使用平均速率限制请求数,
        #第1秒25个请求时,5个请求放到第2秒执行,
        #设置nodelay,25个请求将在第1秒执行。
        limit_req zone=allips  burst=5  nodelay;
	
	#设置用户下载文件的前10m大小时不限速,大于10m后再以256kb/s限速
	##限制下载速度为256KB/秒
	limit_rate_after 10m;
 
	##限制下载速度为256KB/秒
	limit_rate 256k;
	
        location ^~ /wechat-business{  
	    # 这里使用变量 $http_origin取得当前来源域,大家说用“*”代表允许所有,我实际使用并不成功,原因未知;
	    add_header 'Access-Control-Allow-Origin' $http_origin;
	    # 为 true 的时候指请求时可带上Cookie,自己按情况配置吧;
	    add_header 'Access-Control-Allow-Credentials' 'true';
	    # OPTIONS一定要有的,另外一般也就GET和POST,如果你有其它的也可加进去;
	    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

	    # 这个要注意,里面一定要包含自定义的http头字段(就是说前端请求接口时,
	    # 如果在http头里加了自定义的字段,这里配置一定要写上相应的字段),
	    # 从上面可看到我写的比较长,我在网上搜索一些常用的写进去了,里面有“web-token”
	    # 和“app-token”,这个是我项目里前端请求时设置的,所以我在这里要写上;
	    add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
	    
	    # 可不设置,看网上大致意思是默认只能获返回头的6个基本字段,要获取其它额外的,先在这设置才能获取它;
	    # add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
	    
	    add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Length,Content-Range,Range';

	    # 语句“ if ($request_method = 'OPTIONS') { ”,
	    # 因为浏览器判断是否允许跨域时会先往后端发一个 options 请求,然后根据返回的结果判断是否
	    # 允许跨域请求,所以这里单独判断这个请求,然后直接返回;
	    if ($request_method = 'OPTIONS') {
		add_header 'Access-Control-Max-Age' 1728000;
		add_header 'Content-Type' 'text/plain; charset=utf-8';
		add_header 'Content-Length' 0;
		return 204;
	    } 
	    #定义服务器的默认网站根目录位置
	    #root   /root;

            #定义首页索引文件的名称
	    #index index.php index.html index.htm;

	   
	    #以下是一些反向代理的配置,可选。
	    proxy_redirect off;
	    
	    #反向代理,访问后端内容源服务器
	    proxy_set_header Host $host;

	    
	    #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
	    proxy_set_header X-Real-IP $remote_addr;
	    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
	    proxy_set_header X-Forwarded-Proto $scheme;



	    #允许客户端请求的最大单文件字节数
	    client_max_body_size 10m;
	    
	    #缓冲区代理缓冲用户端请求的最大字节数
	    client_body_buffer_size 128k;

            #nginx跟后端服务器连接超时时间(代理连接超时)
	    proxy_connect_timeout 90;


            #后端服务器数据回传时间(代理发送超时)
	    proxy_send_timeout 90;

            #连接成功后,后端服务器响应时间(代理接收超时)
	    proxy_read_timeout 90;

            #设置代理服务器(nginx)保存用户头信息的缓冲区大小
	    proxy_buffer_size 4k;

            #proxy_buffers缓冲区,网页平均在32k以下的设置
	    proxy_buffers 4 32k;

            #高负荷下缓冲大小(proxy_buffers*2)
	    proxy_busy_buffers_size 64k;

            #设定缓存文件夹大小,大于这个值,将从upstream服务器传
	    proxy_temp_file_write_size 64k;
 
	    #请求转向mysvr 定义的服务器列表
	    # API Server 
            proxy_pass http://10.200.111.145:8080/wechat-business;
 
	
            #proxy_pass http://10.10.0.86;
	    
            break;
        }
        location ^~ /appcache-business{  
            #proxy_pass http://localhost:8080/appcache-business;
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~ /waybill-business{  
            #proxy_pass http://localhost:8080/waybill-business;
            proxy_pass http://10.10.0.86;
            break;
        }

	location ^~/openplatform-business {
            proxy_pass http://10.10.0.186;
            break;
        }
	location ^~/sso-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/account-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/base-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/contract-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/crm-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/csm-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/dms-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/finance-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/product-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/order-business {
            #proxy_pass http://localhost:8080/order-business;
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/promotion-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/qc-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/route-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/stl-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/tms-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/user-business{
            proxy_pass http://10.10.0.86;
            break;
        }

        location ^~/vehicle-business {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ^~/wms-business {
            proxy_pass http://10.10.0.86;
            break;
        }

	
	##JSP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
	##本地动静分离反向代理配置
	##所有jsp的页面均交由tomcat或resin处理
        location ~ \.jsp {
	    #定义服务器的默认网站根目录位置
	    root /root;
	    
	    ##使用Web缓存区cache_one
	    fastcgi_cache cache_one;

	    ##对不同的HTTP状态码缓存设置不同的缓存时间
	    fastcgi_cache_valid 200 304 12h;
	    fastcgi_cache_valid 301 302 1m;
	    fastcgi_cache_valid any 1m;

	    
	    ##设置Web缓存的Key值,Nginx根据key值MD5哈希存储缓存,这里根据“域名、URL、参数”组合成Key。
	    fastcgi_cache_key $host$uri$is_args$args;

            ##FastCGI服务器
	    fastcgi_pass 127.0.0.1:9000;
	    fastcgi_index index.jsp;
	    fastcgi_param SCRIPT_FILENAME /home/www/www$fastcgi_script_name;
	    #include fastcgi_params;
	    include fastcgi.conf;
	}


        ##所有静态文件由nginx直接读取不经过tomcat或resin
	#location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)${ 
	    #expires 15d;
	#}

        location ^~ .*\.(js)$ {
            proxy_pass http://10.10.0.86;
            break;
        }
        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {

	    ##限制下载速度为256KB/秒
	    limit_rate 256k;

	    #过期30天,静态文件不怎么更新,过期可以设大一点,如果频繁更新,则可以设置得小一点。
	    expires 30d;
	    break;
        }
        location ~ .*\.(js|css|map|json)$ {
            break;
        }
        location ~ .*\.(js|css|map|json|woff|ttf|eot|svg)$ {
            break;
        }


        location ~ (.*?)/selfMail_2 {
            
	    rewrite ^(.*?)/selfMail_2 $1/branches_order?visitDelivery=0&selectDeptFlag=false&orderWay=2&sourceZoneCode=$arg_sourceZoneCode&customerCode=$arg_customerCode&openid=$arg_openid? permanent;        
        }
	 

        location = / {
            rewrite  "^/+$" /common/login.html break;
        }

        location / {
	     #rewrite ^(.*?)/selfMail_2 $1/branches_order99?visitDelivery=1&selectDeptFlag=false&orderWay=2&sourceZoneCode=$arg_sourceZoneCode&openid=$arg_openid? permanent;
           
	     rewrite   ^(.*?)/?$ /$1.html break;
        }
	#location /images/ {
	#    root "/www";
	#    rewrite ^/images/bbs/(.*\.jpeg)$ /images/$1 break;
	#    rewrite ^/images/www/(.*)$ http://192.168.223.136/$1 redirect;
	#}
 
    }
 
     server {
        listen      86;
        server_name  localhost;

        charset utf-8;
        #access_log  logs/access.log;
	root "D:/auxure";
 

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
            break;
        }

        location ~ .*\.(js|css|map|json)$ {
            break;
        }
		
        location ~ .*\.(js|css|map|json|woff|ttf|eot|svg)$ {
            break;
        }
		
	location = / {
            rewrite / /index.html break;
        }

        location / {
            index  index.html index.htm;  ## 默认站点首页文件
        }
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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


    # HTTPS server
    #
    #server {
    #    listen       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_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

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

##邮箱服务配置
##实现email相关的SMTP/IMAP/POP3代理时,
##共享的一些配置项(因为可能实现多个代理,工作在多个监听地址上)。
mail {
    auth_http  127.0.0.1:80/auth.php;
    pop3_capabilities  "TOP"  "USER";
    imap_capabilities  "IMAP4rev1"  "UIDPLUS";

    server {
        listen     110;
        protocol   pop3;
        proxy      on;
    }

    server {
        listen      25;
        protocol    smtp;
        proxy       on;
        smtp_auth   login plain;
        xclient     off;
    }
}

猜你喜欢

转载自blog.csdn.net/ycb1689/article/details/88916240