配置nginx

2017-08-19  本文已影响0人  小慕先森

(1)nginx运行工作进程个数,一般设置cpu的核心或者核心数x2**
如果不了解cpu的核数,可以top命令之后按1看出来,也可以查看/proc/cpuinfo文件

 grep ^processor /proc/cpuinfo | wc -l 
[root@lx~]# vi/usr/local/nginx1.10/conf/nginx.conf
worker_processes  4;
[root@lx~]# /usr/local/nginx1.10/sbin/nginx-s reload
[root@lx~]# ps -aux | grep nginx |grep -v grep
root 9834  0.0  0.0 47556  1948 ?      Ss  22:36  0:00 nginx: master processnginx
www 10135  0.0 0.0  50088  2004 ?       S    22:58  0:00 nginx: worker process
www 10136  0.0  0.0 50088  2004 ?        S   22:58  0:00 nginx: worker process
www 10137  0.0  0.0 50088  2004 ?        S   22:58  0:00 nginx: worker process
www 10138  0.0  0.0 50088  2004 ?        S   22:58  0:00 nginx: worker process

Nginx****运行CPU亲和力
比如4核配置

(2)Nginx****事件处理模型

events {
  use epoll;
  worker_connections 65535;
  multi_accept on;
}
nginx采用epoll事件模型,处理效率高

work_connections是单个worker进程允许客户端最大连接数,这个数值一般根据服务器性能和内存来制定,实际最大值就是worker进程数乘以work_connections
实际我们填入一个65535,足够了,这些都算并发值,一个网站的并发达到这么大的数量,也算一个大站了!
multi_accept 告诉nginx收到一个新连接通知后接受尽可能多的连接,默认是on,设置为on后,多个worker按串行方式来处理连接,也就是一个连接只有一个worker被唤醒,其他的处于休眠状态,设置为off后,多个worker按并行方式来处理连接,也就是一个连接会唤醒所有的worker,直到连接分配完毕,没有取得连接的继续休眠。当你的服务器连接数不多时,开启这个参数会让负载有一定的降低,但是当服务器的吞吐量很大时,为了效率,可以关闭这个参数。

(3)开启高效传输模式

http {
include mime.types;
default_type application/octet-stream;
……
sendfile on;
tcp_nopush on;
……

Include mime.types; //媒体类型,include 只是一个在当前文件中包含另一个文件内容的指令
default_type application/octet-stream; //默认媒体类型足够
sendfile on;//开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。

注意:如果图片显示不正常把这个改成off。

tcp_nopush on;必须在sendfile开启模式才有效,防止网路阻塞,积极的减少网络报文段的数量(将响应头和正文的开始部分一起发送,而不一个接一个的发送。)

(4)连接超时时间
主要目的是保护服务器资源,CPU,内存,控制连接数,因为建立连接也是需要消耗资源的

keepalive_timeout 60;
tcp_nodelay on;
client_header_buffer_size 4k;
open_file_cache max=102400 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
client_header_timeout 15;
client_body_timeout 15;
reset_timedout_connection on;
send_timeout 15;
server_tokens off;
client_max_body_size 10m;
fastcgi_connect_timeout    600;
fastcgi_send_timeout 600;
fastcgi_read_timeout 600;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
fastcgi_temp_path/usr/local/nginx1.10/nginx_tmp;
fastcgi_intercept_errors on;
fastcgi_cache_path/usr/local/nginx1.10/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128minactive=1d max_size=10g;

注:静态文件不存在会返回404页面,但是php页面则返回空白页!!

fastcgi_cache cache_fastcgi; #表示开启FastCGI缓存并为其指定一个名称。开启缓存非常有用,可以有效降低CPU的负载,并且防止502的错误放生。cache_fastcgi为proxy_cache_path指令创建的缓存区名称

总结:
nginx的缓存功能有:proxy_cache / fastcgi_cache
proxy_cache的作用是缓存后端服务器的内容,可能是任何内容,包括静态的和动态。fastcgi_cache的作用是缓存fastcgi生成的内容,很多情况是php生成的动态的内容。proxy_cache缓存减少了nginx与后端通信的次数,节省了传输时间和后端宽带。fastcgi_cache缓存减少了nginx与php的通信的次数,更减轻了php和数据库(mysql)的压力。

(6)gzip调优
使用gzip压缩功能,可能为我们节约带宽,加快传输速度,有更好的体验,也为我们节约成本,所以说这是一个重点。
Nginx启用压缩功能需要你来ngx_http_gzip_module模块,apache使用的是mod_deflate
一般我们需要压缩的内容有:文本,js,html,css,对于图片,视频,flash什么的不压缩,同时也要注意,我们使用gzip的功能是需要消耗CPU的!

gzip on;
gzip_min_length 2k;
gzip_buffers    4 32k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_typestext/plain text/css text/javascriptapplication/json application/javascript application/x-javascriptapplication/xml;
gzip_vary on;
gzip_proxied any;

(7)expires缓存调优
缓存,主要针对于图片,css,js等元素更改机会比较少的情况下使用,特别是图片,占用带宽大,我们完全可以设置图片在浏览器本地缓存365d,css,js,html可以缓存个10来天,这样用户第一次打开加载慢一点,第二次,就非常快了!缓存的时候,我们需要将需要缓存的拓展名列出来, Expires缓存配置在server字段里面

location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
  expires 30d;
  #log_not_found off;
  access_log off;
}
 
location ~* \.(js|css)$ {
  expires 7d;
  log_not_found off;
  access_log off;
} 

注:log_not_found off;是否在error_log中记录不存在的错误。默认是。
总结:
expire功能优点
(1)expires可以降低网站购买的带宽,节约成本
(2)同时提升用户访问体验
(3)减轻服务的压力,节约服务器成本,是web服务非常重要的功能。 expire功能缺点:

(8)防盗链
防止别人直接从你网站引用图片等链接,消耗了你的资源和网络流量,那么我们的解决办法由几种:
1:水印,品牌宣传,你的带宽,服务器足够
2:防火墙,直接控制,前提是你知道IP来源
3:防盗链策略下面的方法是直接给予404的错误提示

location ~*^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
    valid_referers noneblocked  www.benet.com benet.com;
    if($invalid_referer) {
      #return 302  http://www.benet.com/img/nolink.jpg;
      return 404;
        break;
    }
    access_log off;
 }

参数可以使如下形式:none 意思是不存在的Referer头(表示空的,也就是直接访问,比如直接在浏览器打开一个图片)blocked 意为根据防火墙伪装Referer头,如:“Referer:XXXXXXX”。server_names 为一个或多个服务器的列表,0.5.33版本以后可以在名称中使用“”通配符*。

(9)内核参数优化

注:对于一个TCP连接,Server与Client需要通过三次握手来建立网络连接.当三次握手成功后,我们可以看到端口的状态由LISTEN转变为ESTABLISHED,接着这条链路上就可以开始传送数据了.每一个处于监听(Listen)状态的端口,都有自己的监听队列.监听队列的长度与如somaxconn参数和使用该端口的程序中listen()函数有关
somaxconn参数:定义了系统中每一个端口最大的监听队列的长度,这是个全局的参数,默认值为128,对于一个经常处理新连接的高负载 web服务环境来说,默认的 128 太小了。大多数环境这个值建议增加到 1024 或者更多。大的侦听队列对防止拒绝服务 DoS 攻击也会有所帮助。

下面贴一个完整的内核优化设置:

fs.file-max = 999999
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 10240 87380 12582912
net.ipv4.tcp_wmem = 10240 87380 12582912
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 40960
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.ip_local_port_range = 1024 65000
执行sysctl  -p使内核修改生效

(10)关于系统连接数的优化:

linux 默认值 open files为1024

ulimit -n 1024
说明server只允许同时打开1024个文件
使用ulimit -a 可以查看当前系统的所有限制值,使用ulimit -n 可以查看当前的最大打开文件数。
新装的linux 默认只有1024 ,当作负载较大的服务器时,很容易遇到error: too many open files。因此,需要将其改大
在/etc/security/limits.conf最后增加:

*               soft    nofile          65535
*               hard    nofile          65535
*               soft    noproc          65535
*                hard    noproc          65535

个人配置

#user  nobody;
worker_processes  4;
worker_rlimit_nofile 1024;

#pid        logs/nginx.pid;


events {

        use epoll;

        worker_connections 65535;

        multi_accept on;

}


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


    #access_log  logs/access.log  main;
    log_format  main  '$http_X_Real_IP $http_CLIENTIP $remote_addr $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" $request_time';

    sendfile        on;
    tcp_nopush     on;

    keepalive_timeout  30;
    tcp_nodelay on;
    client_header_buffer_size 4k;
    open_file_cache max=102400 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 1;
    client_header_timeout 15;
    client_body_timeout 15;
    reset_timedout_connection on;
    send_timeout 15;
    server_tokens off;
    client_max_body_size 10m;

    gzip  off;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;

    fastcgi_connect_timeout    600;
    fastcgi_send_timeout 600;
    fastcgi_read_timeout 600;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;

    server {

        listen       80;
        server_name  localhost;
        access_log  /usr/local/logs/nginx/access.log  main;
        root        html;
        index       index.html index.htm index.php;

        #图片缓存时间        
        location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
          expires 30d;
          #log_not_found off;
          access_log off;
        }
        #JS和CSS缓存时间
        location ~* \.(js|css)$ {
          expires 7d;
          log_not_found off;
          access_log off;
        }

        error_page   500 502 503 504  /50x.html;
        location / {
                try_files $uri $uri/ @rewrites;
        }
    
        location @rewrites {
                rewrite ^ /index-development.php last;
        }
    
        location = /robots.txt {
                access_log off;
                log_not_found off;
         }


        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

    }


    # 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;
    #    }
    #}

    #upstream php_group{
    #    server 127.0.0.1:9119 weight=1;
    #    server 127.0.0.1:9120 weight=1;
    #}

    include vhost/*;
}
上一篇 下一篇

猜你喜欢

热点阅读