首页 > 代码库 > 企业级nginx.conf优化参考模板

企业级nginx.conf优化参考模板

以下是我整理的非常实用的企业级nginx.conf优化参考模板,整个配置并不一定适合各种环境,所以需要大家按各自需求选取部分功能配置到自己的nginx配置文件中。

user nginx;     #Nginx服务的默认用户
worker_processes 4;     #一般为CPU核个数
worker_cpu_affinity 001 0010 0100 1000;  #绑定不同Nginx进程到不同CPU上
worker_rlimit_nofile 6535;     #worker进程最大打开文件数,该值受系统进程最大打开文件数限制,
                                # 需要使用命令ulimit -n 查看当前设置
error_log  logs/error.log  info;     #默认错误日志记录路径和级别

#pid        logs/nginx.pid;     #pid文件记录路径

dso {
#       load ngx_http_lua_module.so;    #加载模块
}

events {               #事件处理模型优化
    use epoll;     #使用epoll I/O多路复用模型
    worker_connections  20480;     #单个进程允许的客户端最大连接数,
                                    #该值受系统进程最大打开文件数限制,
                                    #需要使用命令ulimit -n 查看当前设置
}

http {
    include       mime.types;     #文件扩展名与文件类型映射表
    default_type  application/octet-stream;     #默认文件类型
    log_format main ‘$remote_addr - $remote_user [$time_local]  ‘
                    ‘"$request" [$request_uri]  $status $body_bytes_sent $request_body  ‘
                    ‘"$http_referer"  "$http_user_agent" $http_x_forwarded_for  ‘;     #默认日志格式

    server_names_hash_max_size 512;     #默认是512kb,一般要查看系统给出确切的值。这里一般是CPU L1的4-5倍
    server_names_hash_bucket_size 128;     #默认是128kb,与上面参数共享控制保存服务器域名的HASH表,
                                            #大量域名和非常长的域名,可能到达该值。

    sendfile        on;     #开启文件的高效传输模式
    #tcp_nopush     on;     #默认值为off,激活或禁用Linux上的TCP_CORK socket选项,
                            #此选项仅仅当开启sendfile时才生效。
                            #可以允许把http response header和文件的开始部分放在一个文件里发布,
                            #积极作用是减少网络报文段的数量。

    keepalive_timeout  65;     #默认大小75s,设置客户端连接保持会话的超时时间。
    client_body_timeout 15;     #默认值是60s,设置读取客户端请求主体的超时时间。
    send_timeout 25;     #默认值是60s,调用服务器端传送HTTP响应信息到客户端的超时时间

    client_max_body_size 8m;     #默认值是1m,设置最大的允许的客户端请求主体大小

    server_tokens on;     #隐藏Nginx软件版本号信息

    #limit_conn_zone $binary_remote_addr zone=addr:10m;  #设置共享内存区域,配合limit_conn参数
    #limit_req_zone $binary_remote_addr zone=one:10m rete=1r/s; #以请求的客户端IP作为key值,
                                                                #内存区域命令为one,
                                                                #分配10m内存空间,
                                                                #访问速率限制为1秒1次请求(request),
                                                                #配合limit_req参数

    fastcgi_connect_timeout 240;    #默认值是60s,表示Nginx服务器和后端FastCGI服务器连接的超时时间,
                                    # 这个参数通常不超过75s
    fastcgi_send_timeout 240;   #默认值是60s,设置Nginx允许FastCGI服务端返回数据的超时时间
    fastcgi_read_timeout 240;   #设置从Nginx从FastCGI服务器端读取响应信息的超时时间
    fastcgi_buffer_size 64k;    #这是Nginx FastCGI的缓冲区大小参数
    fastcgi_buffers 4 64k;  #默认值是8 4k|8k,设定用来读取从FastCGI服务器端收到的响应信息的缓冲区大小和缓冲区数量
    fastcgi_busy_buffers_size 128k; #默认值为8k|16k,用于设置系统很忙时可以使用的fastcgi_buffers大小,
                                    #官方推荐大小为fastcgi_buffers*2
    fastcgi_temp_file_write_size 128k;  #FastCGI临时文件的大小,可设置为128 - 256 KB
    #fastcgi_temp_path /data/ngx_fcgi_tmp;  #FastCGI临时文件目录
    fastcgi_cache_path /data/ngx_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=40g;
                                            #factcgi_cache缓存目录,
                                            #可以设置目录前列层级,比如2:2会生成256*256个子目录,
                                            #keys_zone是这个缓存空间的名字,cache是用多少内存,inactive表示默认失效时间,
                                            #max_size表示最多用多少硬盘空间,需要注意的是fastcgi_cache缓存是先写在
                                            #fastcgi_temp_path再移到fastcgi_cache_path中去的,所以这两个目录最好在同一个分区

    gzip on; #开启gzip压缩输出
    gzip_min_length 1k; #最小压缩文件大小
    gzip_buffers 4 16k; #压缩缓冲区大小
    gzip_http_version 1.1; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
    gzip_comp_level 2;  #压缩比率。用来指定gzip压缩比,1压缩比最小,
                        #处理速度最快;9压缩比最大,传输速度快,但处理慢,也比较消耗CPU
    gzip_types text/plain  text/css application/x-javascript application/xml; #用来指定压纹的类型
    gzip_disable "MSIE [1-6]."  #设置禁用IE6的gzip压缩
    gzip_vary on;   #vary header支持。

    ############负载均衡配置###########
    upstream default_pools {         #定义动态服务器池
            server 10.0.0.14:33101;
            server 10.0.0.15:33101 down;    #标志服务器不可用,配合ip_hash使用
            server 10.0.0.16:33101;
            ip_hash;    #调度算法
            #check interval=3000 rise=2 fail=5 timeout=1000 type=http;   #添加nginx_upstream_check_module模块,
                                                                         #配置健康检查
    }
    upstream upload_pools {          #定义上传服务器池
        server 10.0.0.9:80 weight=1;    #weight为权重,1-100,数字越大,权重越高

    }
    upstream static_pools {          #定义静态服务器池
        server 10.0.0.10:80 weight=1;
    }
    ############负载均衡配置###########

    #禁止非法域名解析
    server {
        listen 80 default_server;
        server_name _;
        rewrite ^(.*) http://www.test.com$1 permanent;
    }

    # HTTP server
    server {
            listen       80 ;
            server_name  www.test.com ;

            #charset utf-8; #默认编码

            #access_log  logs/host.access.log  main;
            #error_log  logs/host.error.log  main;

            #nginx做反向代理时,限制客户端IP
            if ($remote_addr = 10.0.0.7) {
                return 403;
            }
            if ($remote_addr = 114.114.114.114) {
                set $allow_access_root ‘true‘;
            }

            #利用不同的URI请求,分给不同的服务器池处理
            if ($request_uri ~* "^/upload/(.*)$") {
                proxy_pass http://upload_pools/$1;
            }
            if ($request_uri ~* "^/static/(.*)$") {
                proxy_pass http://static_pools/$1;
            }

            location / {
                #根据不同的客户端设备,转发到不同的服务器池
                if ($http_user_agent ~* "MSIE") {
                    #如果请求的浏览器为微软IE(MSIE),则让请求由static_pools池处理
                    proxy_pass http://static_pools;
                }
                if ($http_user_agent ~* "Chrome") {
                #if ($http_user_agent ~* "Firefox") {
                    #如果请求的浏览器为谷歌浏览器(Chrome),则让请求由upload_pools池处理
                    proxy_pass http://upload_pools;
                }
#                if ($http_user_agent ~* "android") {
#                    proxy_pass http://static_pools;
#                }
#                if ($http_user_agent ~* "iphone") {
#                    proxy_pass http://upload_pools;
#                }

                proxy_pass http://default_pools;
                proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 http_404;
                proxy_set_header Host $host;           #proxy_set_header可实现让代理后端的服务器节点获取访问客户端用户的真实IP
                proxy_set_header X-Real-IP  $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                client_max_body_size 10m; #允许客户端请求的最大单文件字节数
                client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
                proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
                proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
                proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
                proxy_buffer_size 4k; #默认该缓冲区大于等于proxy_buffers设置的大小
                proxy_buffers 4 64k; #设置代理服务器保存用户头信息的缓冲区大小
                proxy_busy_buffers_size 128k; #高负荷下缓冲大小(官方推荐大小proxy_buffers*2)
                proxy_temp_file_write_size 128k;     #设定缓存文件夹大小,大于这个值,将从upstream服务器传
           }
    }

    # HTTPS server
    server {
        listen       443 ssl;
        ssl on;
        server_name  www.test.com ;

        ssl_certificate      test.com_bundle.crt;   #证书
        ssl_certificate_key  test.com.key;          #私钥

        ssl_session_cache    shared:SSL:1m;         #设置缓存类型和大小
        ssl_session_timeout  5m;                    #设置缓存的超时时间

        ssl_ciphers ‘AES128+EECDH:AES128+EDH‘;  #设置ssl加密算法
        ssl_prefer_server_ciphers  on;              #设置服务器加密算法优化于客户端
        ssl_protocols TLSv1.2 TLSv1.1 TLSv1;        #设置ssl支持的加密协议版本

        location / {
            root   /var/www/wordpress;
            index  index.html index.htm index.php;
            #limit_conn addr 10; #限制IP的并发连接10,配合limit_conn_zone参数
            #limit_req zone=one burst=5;    #使用limit_req_zone参数定义的内存空间,队列值为5,即可以有5个请求排除等待
        }

        location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {
            access_log off; #不记录不需要的访问日志
        }

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
           #expires定义用户浏览器缓存的时间为3天,如果静态页面不常更新,可以设置更长,这样可以节省带宽和缓解服务器的压力
           expires      1d;
        }

        #禁止解析指定目录下的指定程序
        location ~ ^/images/.*\.(php|php5|sh|pl|py)$ {
            deny all;
        }

        #禁止访问*.txt和*.doc文件
        location ~* \.(txt|doc)$ {
            if (-f $request_filename) {
                root /var/www/wordpress/files;
                #rewrite ...;   #可以重定向到某个URL
                break;
            }
        }
        location ~* \.(txt|doc)$ {
            root /var/www/wordpress/files;
            deny all;
        }

        #禁止访问指定目录
        location /logs/ {
            deny all;
            #return 404;
        }
        location ~ ^/log/ {
            return 404;
        }
        location ~ ^/(local|log) {
            return 404;
        }

        #限制网站来源IP访问
        location ~ ^/test/ {
            deny 192.168.1.1;
            allow 192.168.1.0/24;
            allow 127.0.0.1;
            deny all;
        }

        #防盗链
        location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
            valid_referers none blocked servernames *.test.com test.com;
            if ($invalid_referer) {
                rewrite ^/ http://www.test.com/img/nolink.jpg;
            }
            access_log off;
            root /var/www/wordpress/images;
            expires 1d;
            break;
        }

        #错误页面跳转
        error_page   400 403 404 405 408 410 411 412 413 414 415 /4xx.html;    #错误页面
        error_page   500 501 502 503 504  /50x.html;    #错误页面

        location ~ .*\.(php|php5)?$ {
            root           /var/www/wordpress ;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            include        fastcgi.conf;

            fastcgi_cache ngx_fcgi_cache;
            fastcgi_cache_valid 200 302 1h; #指定应答代码200 302的缓存时间为1小时
            fastcgi_cache_valid 301 1d; #指定应答代码301的缓存时间为1天
            fastcgi_cache_valid any 1m; #其它应答缓存时间为1分钟
            fastcgi_cache_min_uses 1;   #设置请求几次之后响应将被缓存,1表示一次即被缓存
            fastcgi_cache_use_stale error timeout invalid_header http_500;  #定义在哪些情况下使用过期缓存
            fastcgi_cache_key http://$host$request_uri;    #示例:fast_cache_key $request_method://$host$request_uri;
                                                        #fast_cache_key http://$host$request_uri
                                                        #定义fastcgi_cache的key,注意一定要加上$request_method作为cache key,
                                                        #否则如果先请求的为head类型,后面的GET请求返回为空
        }
    }

#    #TCP负载均衡配置 (nginx1.9.0及以上功能)
#    ######### TCP 反向代理负载均衡设置 ###############
#    upstream tcp_pro {
#        hash $remote_addr consistent;
#        server 10.0.0.14:40003 max_fails=3 fail_timeout=3s;
#        server 10.0.0.16:40003 max_fails=3 fail_timeout=3s;
#    }
#    ######### TCP 反向代理负载均衡设置 ###############
#
#    server {
#        listen 40003;
#        proxy_connect_timeout 2s;
#        proxy_timeout 2s;
#        proxy_pass tcp_pro;
#    }

}

本文出自 “ygqygq2” 博客,请务必保留此出处http://ygqygq2.blog.51cto.com/1009869/1853195

企业级nginx.conf优化参考模板