zoukankan      html  css  js  c++  java
  • 企业级web nginx服务优化

    1.1)隐藏nginx header 内版本号信息

    [root@aliyun ~]# vi /application/nginx/conf/nginx.conf
    http{
    
    ……
    server_tokens off;
    ……
    
    }
    
    [root@aliyun ~]# curl -I 172.19.125.*
    HTTP/1.1 200 OK
    Server: nginx				没有版本号了
    Date: Mon, 11 Sep 2017 07:07:05 GMT
    Content-Type: text/html;charset=utf-8
    Connection: keep-alive
    X-Powered-By: PHP/5.3.27
    Set-Cookie: pcok=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; httponly
    

    1.2)Apache去版本号的参数

    [root@server extra]# cat httpd-default.conf 
    ServerTokens Prod
    ServerSignature off
    

    2.1)更改nginx的默认用户及用户组nobody

    [root@aliyun conf]# grep 'user' nginx.conf.default 
    #user  nobody;
    
    nginx一般都是在编译的时候指定的   --user=nginx  --group=nginx
    

    2.2)apache一般都是在配置文件里面指定

    [root@server conf]# egrep 'User|Group' httpd.conf
    # User/Group: The name (or #number) of the user/group to run httpd as.
    User www
    Group www
    

    3.1)配置nginx worker进程个数 

    在高并发场景,需要事先启动更多的nginx进程以保证快速响应并处理用户的请求
    worker_processes 8;
    建议指定和cpu的数量相等或乘2的进程数。
    [root@aliyun ~]# grep 'physical id' /proc/cpuinfo

    4.1)根据cpu核数进行nginx进程优化

    默认情况下nginx的多个进程可能更多的跑在一颗cpu上,本节是分配不同的进程给不同的cpu处理,达到充分利用硬件多核多cpu的目的。

    四核cpu服务器:
    worker_cpu_affinity 0001 0010 0100 1000;
    nginx进程cpu亲和力,即把不同的进程分给不同的cpu处理。这里0001 0010 0100 1000是掩码,分别代表1、2、3、4颗cpu核心
    
    八核cpu服务器:
    worker_cpu_affinity 0001 0010 0100 1000 0001 0010 0100 1000
    

    压力测试软件    ab ,webbench,,loadruner

    5.1)事件处理模型优化

    nginx的连接处理机制在于不同的操作系统采用不同的io模型,在linxu使用epoll的io多路复用模型,在freebsd使用kqueue的io多路复用模型,在solaris使用/dev/poll方式的io多路复用模型,在windows使用的是icop等等。
    events{
    use epoll;
    }
    use是个事件模块指令,用来指定nginx的工作模式。nginx支持的工作模式有select、poll、kqueue、epoll、rtsig和/dev/poll.其中select和poll都是标准的工作模式,kqueue和epoll是最高效的工作模式,不同的是epoll用在linux平台上,而kqueue用在bsd系统中。对于Linux系统linux2.6+的内核,推荐选择epoll工作模式,这是高性能高并发的设置。

    6.1)调整单个进程允许的客户端最大连接数

    这个值根据服务器性能和程序的内存使用量来指定(一个进程启动使用的内存根据程序确定)

    events{
    worker_connections 20480;			每个进程的最大连接数,默认1024
    }
    

    7.1)配置每个进程最大文件打开数
    worker_rlimit_nofile 65535;
    每个进程打开的最大文件数,可设置为系统优化后的ulimit -HSn的结果,这个可以小一点不必这么大32768就可以。

    8.1)优化服务器名字的hash表大小

    确切名字和通配符名字存储在哈希表中。
    例子:

    server{
    	listen 80;
    	server_name nginx.org www.nginx.org *.nginx.org;
    }
    

    如果定义了大量名字,或者定义了非常长的名字,那就需要在http配置块中调整server_names_hash_max_size和server_names_hash_bucket_size的值。
    server_names_hash_bucket_size的默认值可能是32,或者是64,或者是其他值,取决于cpu的缓存行的长度。如果这个值是32,那么定义“too.long.server.name.nginx.org”作为虚拟主机名就会失败,显示下面错误信息:could not build the server_names_hash,you should increase server_names_hash_bucket_size:32出现了这种情况,那就需要将设置值扩大一倍:

    http{
    	server_names_hash_bucket_size 64;
    }
    

    如果还不能解决问题,或者服务器启动非常缓慢,再尝试提高server_names_hash_bucket_size的值。如果server_name是一个含有捕获组的正则表达式,这是nginx就不得不执行这个表达式以得到捕获组。server_names_hash_max_size 512; #默认是512kb,一般要查看系统给出确切的值,这里一般cpu L1的4-5倍。

    9.1)开启高效文件传输模式

    sendfile on;
    同时将tcp_nopushtcp_nodelay两个指令设置为on用于防止网络阻塞。

    10.1)设置连接超时时间

    php  希望短连接  java长连接

    keepalive_timeout 60;
    客户端连接保持会话的超时时间,超过这个时间,服务器会关闭该连接。
    tcp_nodelay on;
    包含了keepalive参数才有效
    client_header_timeout 15;
    设置客户端请求头读取超时时间,如超过这个时间,客户端还没有发送任何数据,nginx将返回“Request time out(408)”错误。
    client_body_timeout 15;
    设置客户端请求主体读取超时时间,如超过这个时间,客户端还没有发送任何数据,nginx将返回“request time out(408)”错误,默认值是60.
    send_timeout 15;
    响应客户端的超时时间。这个超时仅限于两个连接活动之间的时间,如果超过这个时间,客户端没有任何活动,nginx将会关闭连接
    

    11.1)上传文件大小限制(动态应用)

    主配置文件里加入如下参数
    client_max_body_size 10m;
    官方文档:
    set the maximum allowed size of the client request body

    12.1)fastcgi调优(配合php引擎动态服务)

    fastcgi_connect_timeout 300;
    连接到后端fastcgi的超时时间
    fastcgi_send_timeout 300;
    向fastcgi传送请求的超时时间,这个值是指已经完成两次握手后向fastcgi传送请求的超时时间。
    fastcgi_read_timeout 300;
    接收fastcgi应答的超时时间,这个值是指已经完成两次握手后接收fastcgi应答的超时时间。
    fastcgi_buffer_size 64k;
    读取fastcgi应答第一部分需要用多大的缓冲区,这个值表示将使用1个64KB的缓冲区读取应答的第一部分(应答头),
    可以设置为fastcgi_buffers选项指定的缓冲区大小。
    fastcgi_buffers 4 64k;
    本地需要用多少盒多大的缓冲区来缓冲fastcgi的应答请求。如果一个php脚本所产生的页面大小为256KB,那么会为其分配4个64KB的缓冲区来缓冲;如果页面大小大于256KB,那么大于256KB的部分会缓存到fastcgi_temp指定的路径中,但是这并不是好方法,因为内存中的数据处理速度要快鱼硬盘,一般这个值应该为站点中Php脚本所产生的页面大小的中间值,如果站点大部分脚本所产生的页面大小为256KB,那么可以把这个值设置为“16” 、“4 64k”等。
    fastcgi_busy_buffers_size 128k;
    建议为fastcgi_buffers的两倍
    fastcgi_temp_file_write_size 128k;
    在写入fastcgi_temp_path时将用多大的数据块,默认值是fastcgi_buffers的两倍,设置上述数值设置太小时若负载上来时可能报502BAD GATEWAY
    fastcgi_cache oldboy_nginx;
    开启fastcgi缓存并为其指定一个名称。开启缓存非常有用,可以有效降低cpu的负载,并且防止502错误的发生,但是开启缓存也可能会引起其他问题。
    fastcgi_cache_valid 200 302 1h;
    用来指定应答代码的缓存时间,实例中的值表示将200和302应答缓存一个小时
    fastcgi_cache_valid 301 1d;
    将301应答缓存1天
    fastcgi_cache_valid any 1m;
    将其他应答缓存为1分钟
    fastcgi_cache_min_uses 1;
    缓存在fastcgi_cache_path指令inactive参数值时间内的最少使用次数
    

    13.1)更改源码隐藏软件名称及版本号

    #修改/home/tools/nginx-1.6.2/src/core
    
    隐藏软件名称等操作
    /home/tools/nginx-1.6.2/src/http
    [root@aliyun http]# vim ngx_http_header_filter_module.c 
    
    48行
    static char ngx_http_server_string[] = "Server: nginx" CRLF;
    static char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;
    改为
    static char ngx_http_server_string[] = "Server: nidaye" CRLF;
    static char ngx_http_server_full_string[] = "Server: nidaye " CRLF;
    
    此时就需要重新编译,需要备份的东西要备份,,,这面这个操作只改变了header,对于页面错误的信息要该下面与上相同目录,,,,这个最好跟上面的一起做了,不要重复编译
    [root@aliyun http]# vim ngx_http_special_response.c 
    
    static u_char ngx_http_error_tail[] =
    "<hr><center>nidaye</center>" CRLF
    "</body>" CRLF
    "</html>" CRLF
    ;
    

    14.1)配置nginx gzip压缩模块

    提供了对文件内容压缩的功能,允许nginx服务器将输出内容在发送到客户端之前根据具体的策略进行压缩,以节约网站带宽,同时提升用户访问体验,此功能同apache的mod_deflate压缩功能,依赖ngx_http_gzip_module模块,默认已安装。

    需要压缩的所有程序(js,css,html,文本),不要压缩的内容(图片,视频,flash)

    gzip on;
    开启gzip压缩功能
    gzip_min_length 1k;
    允许压缩的页面最小字节数,页面字节数从header头的content-length中获取,默认值是0,不管哪个页面多大都进行压缩,建议设置成大于1k,如果小于1k可能会越压越大。
    gzip_buffers   4 32k;
    申请4个单位为16k的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。
    gzip_http_version 1.1;
    压缩版本(默认1.1,前端为squid2.5时使用1.0)用于设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持gzip解压,使用默认即可。
    gzip_comp_level 9;
    压缩比率。用来指定gzip压缩比,1压缩比最小,处理速度最快;9压缩比最大,传输速度快,但处理最慢,比较消耗cpu资源
    gzip_types text/plain application/javascript text/css application/xml;			可以在nginx下的[root@aliyun conf]# cat mime.types查看类型,不同的版本可能不同,火狐有个插件yslow可以查看压缩情况,可能需要翻墙下载用来指定压缩的类型,“text/html”类型总是会被压缩。。
    gzip_vary on;
    可以让前端的缓存服务器缓存经过gzip压缩的页面,缓存服务器里保存压缩过的缓存。
    

    apache压缩模块

    以DSO动态模块加载mod_deflate配置的全部命令为: cd /home/oldboy/tools/httpd-2.2.27/modules/filters/ 
    <==切到apache软件目录mod_deflate程序下。
    /application/apache/bin/apxs -c -i -a mod_deflate.c 
    <==以dso的方式编译入到apache中。
    ll /application/apache/modules/mod_deflate.so 
    <==检查mod_deflate
    
    配置文件的修改
    <ifmodule mod_deflate.c> 
    	DeflateCompressionLevel 9 
    	SetOutputFilter DEFLATE 
    	AddOutputFilterByType DEFLATE text/html text/plain text/xml 
    	AddOutputFilterByType DEFLATE application/javascript 
    	AddOutputFilterByType DEFLATE text/css
     </ifmodule>
     
    

    15.1)nginx expires缓存功能

    为了缓解网站访问的访问压力,我们应该尽量将客户访问内容往前推,能够放到客户端的就不要放到CDN,能够放到CDN的就不用放到本地服务器,充分的利用每一层的缓存,直到万不得已才让客户访问到我们的数据存上去。

    expires
    好处:
      1、第一次以后,访问网站快
      2、节省服务带宽,,,成本
      3、服务器压力降低。成本
    坏处:
      1、网站改版,对应的用户看到的还是旧的(js,css,图片)

    解决坏处:
      1、过期的时间短一些。
      2、资源文件更新时,改名。

    配置ngxin expires,,,,这个需要放在server标签下

    1、根据文件扩展名进行判断
    location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ 
    { 
          expires 3650d; 
    	  root    html/bbs;
    }
    location ~ .*.(js|css)?$ 
    { 
          expires 30d;
    	  root    html/bbs;
    }
    
    
    2、根据目录进行判断
    ## Add expires header according to dir. 
    location ~ ^/(images|javascript|js|css|flash|media|static)/ { 
    	expires 360d; 
    }
    
    3、单个文件判断
    给robots.txt设置过期时间,这里为robots为7天并不记录404错误日志
    location ~(robots.txt){
    	log_not_found off;
    	expires 7d;
    	break;
    	
    }
    

    apache的这个过期时间跟上面的压缩源码添加差不多,但是为了省去麻烦还是在编译的时候就设置好

    ExpiresActive on 
    ExpiresDefault "access plus 12 month"
    ExpiresByType text/html "access plus 12 months" 
    ExpiresByType text/css "access plus 12 months"
    ExpiresByType image/gif "access plus 12 months" 
    ExpiresByType image/jpeg "access plus 12 months"
    ExpiresByType image/jpg "access plus 12 months" 
    ExpiresByType image/png "access plus 12 months"
    EXpiresByType application/x-shockwave-flash "access plus 12 months"
    EXpiresByType application/x-javascript "access plus 12 months" 
    ExpiresByType video/x-flv "access plus 12 months"
    

    16.10)nginx防爬虫案例

    参考:http://blog.csdn.net/xifeijian/article/details/38615695

    防止客户端是火狐或者IE的访问,,,,,,不同的爬虫所对应的agent也是不一样的

    if ($http_user_agent ~* "Firefox|MSIE") 
    { 
    	return 403;
    }
    
    
    下面是在真个篇幅下,这个的所处位置环境
    server {
    			listen       80;
    			server_name  bbs.etiantian.org;
    				root   html/bbs;
    				index  index.php  index.html index.htm;
    			if ($http_user_agent ~* "Firefox|MSIE") 
    			{ 
    				return 403; 
    			}
    			location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ 
    			{ 
    					expires 3650d;
    				root    html/bbs; 
    			}
    			location ~ .*.(js|css)?$ 
    			{ 
    					expires 30d;
    				root	html/bbs;
    			}
    			 location ~.*.(php|php5)?$ {
    			 root           html/bbs;
    			 fastcgi_pass   127.0.0.1:9000;
    			 fastcgi_index  index.php;
    			# fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    			 include        fastcgi.conf;
    			}
    		}
    

    ~ 区分大小写(大小写敏感)匹配成功
    ~* 不区分大小写匹配成功
    !~ 区分大小写匹配失败
    !~* 不区分大小写匹配失败

    17.1)nginx日志轮询

    mkdir /server/scripts/ -p
    cd /server/scripts/
    vim cut_nginx_log.sh
    cd /application/nginx/logs && 
    /bin/mv www_access.log www_access_$(date +%F -d -1day).log
    /application/nginx/sbin/nginx -s reload
    

    然后将这段脚本加入crontab

    18.1)NGINX不记录不需要的访问日志,对于健康检查或某些图片不需要记录,而且日志写入频繁会消耗磁盘IO,降低服务性能。

    location ~ .*.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ 
    { 
    	access_log off; 
    } 
    

    apache呢

    配置方法:
    <FilesMatch ".(css|js|gif|jpg|ico|swf)"> 
    SetEnv IMAG 1 
    </FilesMatch> 
    日志配置:
    CustomLog "|/usr/local/sbin/cronolog /app/logs/%Y/%m/access_%Y%m%d.log" combined env=!IMAG 
    CustomLog "|/usr/local/sbin/cronolog /app/logs/%Y/%m/%d/access_%Y%m%d%H.log" combined env=!IMAG
    

    19.1)最小化目录及文件权限设置

    安全的权限:
    所有站点目录的用户和组都应该为root
    所有目录权限是默认的755
    所有文件权限是默认的644
    注意,网站服务的用户不能用root。
    以上的权限的设置可以做到防止黑客上传木马,以及修改站点文件,但是合理的用户上传的内容也被拒之门外了。====
    要解决上面的问题,,,就要对业务进行分离,在比较好的网站架构中,应把资源文件,包括用户上传的图片,附件等的服务和程序服务分离,最好把上传程序服务也分离,这样就可以从容按照前面安全的标准授权了。

    20.1)nginx站点目录及文件URL访问控制

    根据扩展名限制程序和文件访问

    1)nginx下禁止访问资源目录下的PHP程序被解析,禁止images目录下的php文件被访问

    location ~ ^/images/.*.(php|php5)$ {
    	deny all;
    }
    
    location ~ ^/static/.*.(php|php5)$ {
    	deny all; 
    } 
     
    location ~* ^/data/(attachment|avatar)/.*.(php|php5)$ { 
    	deny all; 
    }
    
    但是上面这些需要放在下面的前面
    location ~.*.(php|php5)?$ {
    	     root           html/bbs;
    	     fastcgi_pass   127.0.0.1:9000;
    	     fastcgi_index  index.php;
    	     include        fastcgi.conf;
    	 }
    

    2)Nginx下配置禁止访问*.txt文件

    location ~* .(txt|doc)$ { 
    	if (-f $request_filename){ 
    		root /data/www/www; 
    		#rewrite …..可以重定向到某个URL 
    		break;
    	}
     } 
     
    location ~* .(txt|doc)${ 
    root /data/www/www; 
    deny all;
    }
    
    单目录: 
    location ~ ^/(static)/ {
    	deny all; 
    } 
    location ~ ^/static { 
    	deny all;
    } 
    多目录: 
    location ~ ^/(static|js) { 
    	deny all; 
    }
    location /admin/ { 
    	return 404;
    } 
    location /templates/ {
    	return 403; 
    }
    

    禁止某目录让外界访问,但允许某ip访问该目录,且支持PHP解析

    location ~ ^/oldboy/ { 
    	allow 202.111.12.211; 
    	deny all; 
    } 
    
    location / { 
    	deny 192.168.1.1; 
    	allow 192.168.1.0/24; 
    	allow 10.1.1.0/16; 
    	deny all; 
    }
    

    状态码:http://oldboy.blog.51cto.com/2561410/716294
    消息(1字头)
    成功(2字头)
    重定向(3字头)
    请求错误(4字头)
    服务器错误(5字头)

    21.1)优雅的错误页面

    在server标签下
    error_page 403 /403.html   此路径相对于root    html/www的
    
    error_page 500 502 503 504 /50x.html;
    location = /50x.html{
    	root html;
    }
    位于html目录下
    

     

    门户网站案例
    error_page 400 http://err.tmall.com/error1.html; 
    error_page 403 http://err.tmall.com/error1.html; 
    error_page 404 http://err.tmall.com/error1.html; 
    error_page 405 http://err.tmall.com/error1.html;
    error_page 408 http://err.tmall.com/error1.html; 
    error_page 410 http://err.tmall.com/error1.html; 
    error_page 411 http://err.tmall.com/error1.html; 
    error_page 412 http://err.tmall.com/error1.html; 
    error_page 413 http://err.tmall.com/error1.html;
    error_page 415 http://err.tmall.com/error1.html; 
    error_page 500 http://err.tmall.com/error2.html; 
    error_page 501 http://err.tmall.com/error2.html; 
    error_page 502 http://err.tmall.com/error2.html; 
    error_page 503 http://err.tmall.com/error2.html; 
    error_page 506 http://err.tmall.com/error2.html;
    
    淘宝的web服务器
    http://tengine.taobao.org/
    

    22.1)使用tmpfs文件系统代替频繁访问的目录

    tmpfs,临时文件系统,是一种基于内存的文件系统。
    
    可以配置eaccelerator缓存目录
    mkdir -p /tmp/eaccelerator
    此目录可以用tmpfs内存文件系统来存储,ssd固态硬盘
    chown -R nginx.nginx /tmp/eaccelerator
    
    也可以重新搞一个目录
    [root@aliyun ~]# mkdir -p /tmpfs
    [root@aliyun ~]# mount -t tmpfs -o size=16m tmpfs /tmpfs
    [root@aliyun ~]# df -h
    Filesystem      Size  Used Avail Use% Mounted on
    /dev/vda1        40G  5.4G   32G  15% /
    tmpfs           499M     0  499M   0% /dev/shm
    tmpfs            16M     0   16M   0% /tmpfs
    
    -t 类型      第二个tmpfs是设备名    正常情况下可以设置空间为2G到4G
    然后可以放到/etc/fstab或者/etc/rc.loacl 
    

    23.1)apache不解析php

    方法1:提示下载不解析
    <Directory ~ "/application/www/etiantian/bbs/attachments"> 
    	Options FollowSymLinks 
    	AllowOverride None
    	Order allow,deny 
    	Allow from all 
    	php_flag engine off #注意这行
    </Directory>
    
    
    方法2:这个会包含403
    <Directory /var/html/blog>
    	<Files ~ ".php"> 
    		Order allow,deny 
    		Deny from all
    	</Files> 
    </Directory>
    

    24.1)Tcmalloc优化Nginx性能(自己判断要不要使用)
    TCMalloc的全称为Thread-Caching Malloc,是谷歌开发的开源工具“google-perftools”中的一个成员。与标准的glibc库的malloc相比,TCMalloc库在内存分配效率和速度上要高很多,这在很大程度上提高了服务器在高并发情况下的性能,从而降低系统负载。下面简单介绍如何为Nginx添加TCMalloc库支持。

    25.1)

    vim proxy.conf
    
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    client_max_body_size 50m;
    client_body_buffer_size 256k;
    proxy_connect_timeout 30;
    proxy_send_timeout 30;
    proxy_read_timeout 60;
     
    proxy_buffer_size 4k;
    proxy_buffers 4 32k;
    proxy_busy_buffers_size 64k;
    proxy_temp_file_write_size 64k;
    proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
    proxy_max_temp_file_size 128m;
    proxy_store on;
    proxy_store_access   user:rw  group:rw  all:r;
    #proxy_temp_path      /dev/shm/nginx_proxy;
    #proxy_temp_path       /data2/nginx_cache;
    
    然后再具体的站点的下面
    例如
    location ~.*.(php|php5)?$ {
    	     root           html/bbs;
    	     fastcgi_pass   127.0.0.1:9000;
    	     fastcgi_index  index.php;
    	    # fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    	     include        fastcgi.conf;
    	     include        proxy.conf;
    	 }
    
    配置文件在conf下,,,然后配置在extra下的虚拟主机里
    

    25.1)Nginx多实例,,,,,指定不同的配置文件,不同的端口就可以实现多实例

      

  • 相关阅读:
    2、容器初探
    3、二叉树:先序,中序,后序循环遍历详解
    Hebbian Learning Rule
    论文笔记 Weakly-Supervised Spatial Context Networks
    在Caffe添加Python layer详细步骤
    论文笔记 Learning to Compare Image Patches via Convolutional Neural Networks
    Deconvolution 反卷积理解
    论文笔记 Feature Pyramid Networks for Object Detection
    Caffe2 初识
    论文笔记 Densely Connected Convolutional Networks
  • 原文地址:https://www.cnblogs.com/bill2014/p/7524915.html
Copyright © 2011-2022 走看看