Nginx优化

一 软件优化

    优化前

[root@centos7 ~]# curl -I http://192.168.10.242
HTTP/1.1 200 OK
Server: nginx/1.15.2
Date: Sat, 11 Aug 2018 03:26:17 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Fri, 10 Aug 2018 03:58:00 GMT
Connection: keep-alive
ETag: "5b6d0d48-264"
Accept-Ranges: bytes

1.1.1 隐藏Nginx软件版本号(http标签内)

[root@centos7 ~]# vim /usr/local/nginx/conf/nginx.conf
    server_tokens off;

验证:

[root@centos7 ~]# vim /usr/local/nginx/conf/nginx.conf
[root@centos7 ~]# nginx -t
nginx: the configuration file /usr/local/nginx-1.15.2/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx-1.15.2/conf/nginx.conf test is successful
[root@centos7 ~]# systemctl restart nginx
[root@centos7 ~]# curl -I http://192.168.10.242
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 11 Aug 2018 03:28:36 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Fri, 10 Aug 2018 03:58:00 GMT
Connection: keep-alive
ETag: "5b6d0d48-264"
Accept-Ranges: bytes

1.1.2 优化Nginx软件名称

修改源码

vim /root/nginx-1.15.2/src/core/nginx.h
/*
 * Copyright (C) Igor Sysoev
 * Copyright (C) Nginx, Inc.
 */
#ifndef _NGINX_H_INCLUDED_
#define _NGINX_H_INCLUDED_
#define nginx_version      1015002
#define NGINX_VERSION      "8.09.2"   #修改版本号
#define NGINX_VER          "Yan/" NGINX_VERSION
#ifdef NGX_BUILD
#define NGINX_VER_BUILD    NGINX_VER " (" NGX_BUILD ")"
#else
#define NGINX_VER_BUILD    NGINX_VER
#endif
#define NGINX_VAR          "Yan"
#define NGX_OLDPID_EXT     ".oldbin"
#endif /* _NGINX_H_INCLUDED_ */


vim /root/nginx-1.15.2/src/http/ngx_http_header_filter_module.c
49 static u_char ngx_http_server_string[] = "Server: Yan" CRLF;

vim /root/nginx-1.15.2/src/http/ngx_http_special_response.c 
 36 "<hr><center>Yan</center>" CRLF

验证:

[root@centos7 sbin]# curl -I  http://192.168.10.247
HTTP/1.1 200 OK
Server: Yan/8.09.2
Date: Sat, 11 Aug 2018 04:10:14 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Sat, 11 Aug 2018 04:08:10 GMT
Connection: keep-alive
ETag: "5b6e612a-264"
Accept-Ranges: bytes

1.1.3 定义Nginx运行的用户和用户组

user  nginx nginx;

二 优化Nginx性能

2.1.1 优化nginxworker进程数(初始可设置为CPU总核数)也可以设置为auto nginx会自动根据核心数为生成对应数量的worker进程

worker_processes  2;

2.1.2 CPU亲和力 把不同的进程绑定在不用的cup  0001 代表cpu掩码

worker_cpu_affinity 0001 0010 0100 1000                          #四核cpu
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 1000
0000                                                             #八核cpu

2.1.3 Nginx事件处理模型(events)事件里配置  Nginx默认选择最佳模型

具体模型资料可以看下官网或者:https://blog.csdn.net/ghost_leader/article/details/72902580

    use epoll;

2.1.4 Nginx单个进程允许客户端最大链接数(events)

    worker_connections  4096;

2.1.5 Nginx work进程最大打开文件数 放置主标签段

worker_rlimit_nofile 65535;
events {
    use epoll;
    worker_connections 20480;
}

2.1.6 开启文件高效传输,防止网络以及磁盘I/O阻塞,提升Nginx工作效率 tcp_nopush和tcp_nodelay同时使用

官网:http://nginx.org/en/docs/http/ngx_http_core_module.html#sendfile

放置位置:http,server,location  (拷贝函数实现内核零拷贝)

    sendfile        on;    
    tcp_nopush      on;    #可以把http response header和文件到开始放在一个文件里发布,减少网络报文数量。
tcp_nodelay on; #提高I/o性能,

2.1.7  服务器端链接超时(http标签)

    keepalive_timeout  65;

2.1.8 Nginx读取客户端请求头部信息超时(http标签)

client_header_timeout 15s;

2.1.9 Nginx读取客户端请求主体超时(http标签)

client_body_timeout 60s;

2.2.0 Nginx指定形影客户端超时时间(http标签)

send_timeout 60s;

2.2.1 客户端上传文件大小控制(具体看业务)(http标签)

    client_max_body_size 8m;

2.2.2 指定字符集(server标签)

    charset utf-8;

2.2.3 404优雅提示

        error_page  404 403              /404.html;
        error_page  404 403              http://www.baidu.com;

三 fastcgi相关优化

官网地址:http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html

3.1.1 Nginx服务器和后端FastCGI服务器连接的超时时间

    fastcgi_connect_timeout 30;

3.1.2 Nginx允许FastCGI服务端返回数据的超时时间

 fastcgi_send_timeout 15;

3.1.3 Nginx从FastCGI服务端读取响应信息的超时时间

fastcgi_read_timeout 15;

3.1.4 Nginx读取响应信息的超时时间

fastcgi_read_timeout 15;

3.1.5 读取从FastCGI服务端收到的第一部分响应信息的缓冲区大小

fastcgi_buffer_size 64k;

3.1.6 读取从FastCGI服务端收到的响应信息的缓冲区大小以及缓冲区数量

fastcgi_buffers 4 64k;

3.1.7 系统很忙时可以使用的fastcgi_buffers大小,推荐大小为fastcgi_buffers *2。

fastcgi_busy_buffers_size 128k;

3.1.8 fastcti临时文件的大小,可设置128-256K

fastcgi_temp_file_write_size 512k;

3.2.9 设置fastcgi_cache存储路径

#fastcgi_temp_path:生成fastcgi_cache临时文件目录 cache的目录,采用二级目录hash,256*256目录分级,设置缓存内存空间为100m,官方文档给出的1m能够容纳8000个cache key,最大硬盘占用空间为10g,是所有cache文件所占用硬盘的限制值   
     fasrcgi_cache_path /tmp/ngx_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:100m inactive=1d max_size=10g;  

3.2.0 fastcgi_cache

      location ~.*.(php|php5)?% {
#设置fastcg的临时目录,cache存放的时候是首先放到这个目录然后移动到cache目录中,官方文档要求这两个目录位于同一个分区以保证性能
         #fastcgi_temp_path /tmp/ngx_fcgi_tmp 1 2;
#fscg路径
       fastcgi_pass 127.0.0.1:9000;
#指定index
       fastcgi_index index.php;  
 #导入配置文件 
       include fastcgi.conf;
#当一次请求过来需要写一个cache key的时候,会把这个key锁住,目的是当多个请求同时请求写同一个key的时候只有一个可以去写,其它的等待该key写成功后直接从cache中取,防止了大量请求下穿透cache给后端fastcgi造成过大的压力 
      fastcgi_cache_lock on; 
#设置锁过期的时间
       fastcgi_cache_lock_timeout 1s;
 #用哪个缓存空间(在http层中我们定义的keys_zone
          fastcgi_cache ngx_fcgi_cache;    
#定义哪些http头要缓存 示例中200 302 都是1h 缓存301d等 其他的状态是1分钟缓存
          fastcgi_cache_valid 200 302 1h; #
          fastcgi_cache_valid 301 1d;
          fastcgi_cache_valid any 1m;
#请求几次之后缓存
          fastcgi_cache_min_uses 1;
#定义那些情况下使用过期缓存
          fastcgi_cache_use_stale error timeout invalid_header http_500;
#定义fastcgi_cache的key
          fastcgi_cache_key http://$host$request_uri;

}

四 Nginx压缩优化

功能介绍:

    Nginx gzip压缩模块提供了压缩文件内容的功能,用户请求的内容发送出去到用户端前Nginx会根据一些策略来进行压缩,节约出站口带宽,加快了输出传输效率,提升了用户体验。

    传文本压缩比高 如html,js,css

    图片,视频等文件尽量不压缩,压缩会消耗大量cpu,内存等资源。

4.1.1 开启gzip压缩

    gzip  on;

4.1.2 允许压缩页面的最小字节,页面字节数从header头的content-lenget中获取

    gzip_min_length  1k;

4.1.3 压缩缓冲区

    gzip_buffers     4 16k;

4.1.4 压缩版本识别http协议版本

    gzip_http_version 1.1;

4.1.5 压缩级别 1压缩比最小处理最快;9压缩级别比最大,传输速度快但是处理慢,消耗资源

    gzip_comp_level 6;

4.1.6 指定类型

    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
查看媒体类型

[root@centos7 ~]# cd /usr/local/nginx/conf/
[root@centos7 conf]# less mime.types

4.1.7 vary header支持。可以让前端的cnd缓存服务器可以缓存gzip页面而不解压

    gzip_vary on;

4.1.8 对ie6浏览器不压缩 IE6对Gzip不怎么友好,不给它Gzip了

    gzip_disable    "MSIE [1-6].";

五 Nginx expires缓存优化

   通过用户访问网站内容进行缓存,用户下次访问如果没达到过期时间就不进行更新下载,使用本地缓存,也可以说是浏览器缓存

作用:

    降低网站带宽

    提高网站速速,提升用户体验

   降低了服务器访问量,减轻了服务器压力

5.1.1 对后缀名进行缓存

        location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {
          expires 365d;
        } 

5.1.2 对js,css文件进行缓存

        location ~ .*.(js|css)?$ {
          expires 30d;
        }

5.1.3 对目录进行缓存

        location ~ ^/(images|js|css|media|static)/ {
           expires 360d;
        }

 六 对服务器目录以及文件URL访问控制

6.1.1 禁止指定目录

    location ~ ^/images/.*.(php|php5|.sh|.pl|.py)$ {
      deny all;
}   

6.1.2 禁止指定目录

    location ~* ^/data/(images|data)/.*.(php|php5)$ {
      deny all;
}

6.1.3 禁止访问目录

    location ~ ^/(static|app) {
      deny all;
}

七 限制网站来源IP访问

    location ~ ^/data/ {
      allow 192.68.10.5;
      deny all;
}
    location ~ {
     deny 192.168.1.1;
     allow 192.168.1.0/24;
     deny all;
}
if ( $remote_addr = 192.168.10.10 ) {
    return 403;
}

八  禁止非法域名解析访问企业网站

    server {
        listen 80 default_server;
        server_name_;
        return 501;
    }

九 图片以目录防盗链

      location ~* ^.+.(jpg|png|swf|flv|rar|zip)$ {
            valid_referers none blocked *.yanshao.com yanshao.com;
            if ($invalid_referer) {
               rewrite ^/ http://www.yanshao.com/img/nolink.gif;
            }
            root html/www;
        }
原文地址:https://www.cnblogs.com/yanshicheng/p/9460246.html