• Nginx 优化(一)


    系统优化:

    文件句柄,文件描述符,会随着进程数增加而增加。

    1.查看文件句柄命令

    #查看文件句柄数设置
    [root@web01 ~]# ulimit -n
    65535

    #查看总共打开的文件句柄数
    [root@web01 ~]# lsof | wc -l

    #查看进程打开的文件句柄数
    [root@web01 ~]# lsof -p 71336 | wc -l
    32

    2.设置文件句柄数

    1)系统全局设置

    [root@web01 ~]# vim /etc/security/limits.conf
    * - nofile 65535
    * soft nofile 65535
    * hard nofile 65535
    *       #代表所有用户
    -       #超过文件句柄数时,什么都不干
    soft    #超过文件句柄数时,仅提示
    hard    #超过文件句柄数时,直接限制

    2)用户局部设置

    [root@web01 ~]# vim /etc/security/limits.conf
    root - nofile 65535
    root soft nofile 65535
    root hard nofile 65535

    3)针对nginx服务

    [root@web01 ~]# vim /etc/nginx/nginx.conf
    user www;
    worker_processes 1;
    worker_rlimit_nofile 65535;

    2.系统优化

    [root@web01 ~]# vim /etc/sysctl.conf
    net.ipv4.tcp_fin_timeout = 2
    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_tw_recycle = 1
    net.ipv4.tcp_syncookies = 1
    net.ipv4.tcp_keepalive_time = 600
    net.ipv4.ip_local_port_range = 4000 65000
    net.ipv4.tcp_max_syn_backlog = 16384
    net.ipv4.tcp_max_tw_buckets = 36000
    net.ipv4.route.gc_timeout = 100
    net.ipv4.tcp_syn_retries = 1
    net.ipv4.tcp_synack_retries = 1
    net.core.somaxconn = 16384
    net.core.netdev_max_backlog = 16384
    net.ipv4.tcp_max_orphans = 16384
    net.ipv4.ip_forward = 1

    [root@web01 ~]# sysctl -p        ##重启让配置生效

    nginx做代理的优化

    nginx作为代理,负责转发用户的请求,如果不配置默认是短链接,需要手动配置

    1.配置nginx代理开启长连接

    [root@lb01 ~]# vim /etc/nginx/conf.d/proxy.conf
    upstream web {
    server 172.16.1.7:80;
    keepalive 16;       #开启长连接
    }

    server {
    listen 80;
    server_name linux.node.com;

    location / {
    proxy_pass http://web;
    proxy_http_version 1.1;        #指定长连接版本
    include /etc/nginx/proxy_params;
    }
    }

    2.配置nginx代理PHP开启长连接

    [root@web01 ~]# cat /etc/nginx/conf.d/linux.blog.com.conf
    server {
    listen 80;
    server_name linux.blog.com;
    root /code/wordpress;

    location ~* .php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_keep_conn on; #配置代理http开启长连接
    include fastcgi_params;
    }
    }

    nginx处理静态资源优化

    nginx作为静态资源服务器,用于处理静态资源非常的高效

     1.静态资源缓存

    1)浏览器缓存

    #响应头部
    cache-control: max-age=2592000
    expires: Thu, 19 Nov 1981 08:52:00 GMT
    ETag: "5f3fefc8-2d03"
    Last-Modified: Fri, 21 Aug 2020 16:01:12 GMT
    #请求头部
    If-Modified-Since: Fri, 21 Aug 2020 16:01:12 GMT
    If-None-Match: "5f3fefc8-2d03"



    2)浏览器读取缓存流程

    1.浏览器会先去查看响应头部的cache-control(缓存控制)
    2.如果没有到达过期时间,会直接返回缓存中的内容,不需要重新读取服务器
    3.如果cache-control设置为 no-cache,浏览器会去读取expires(缓存过期时间)
    4.如果没有到达expires过期时间,会直接返回缓存中的内容,不需要重新读取服务器
    5.如果cache-control和expires都没有设置
    6.浏览器会去查看服务器上面ETag值,如果有浏览器会拿着 If-None-Match 去跟他对比
    7.如果ETag与浏览器的 If-None-Match 相同,则走缓存
    8.如果ETag与浏览器的 If-None-Match 不相同,浏览器会去查看服务器上面 Last-Modified值
    9.如果服务器上有 Last-Modified值,浏览器会拿着If-Modified-Since去跟他对比
    10.如果Last-Modified值与浏览器的 If-Modified-Since 相同,则走缓存
    11.如果Last-Modified值与浏览器的 If-Modified-Since 不相同,重新去服务器读取数据
    #含义
    1.cache-control:缓存控制,记录的时文件保留时间
    2.expires:缓存时间,记录的是文件的过期时间
    3.ETag:服务器上保留的文件唯一标识符
    4.If-None-Match:浏览器上保留的文件唯一标识符
    5.Last-Modified:服务器上保留的文件最后修改时间
    6.If-Modified-Since:浏览器上保留的文件最后修改时间



    3)配置缓存过期时间

    #语法
    Syntax: expires [modified] time;
            expires epoch | max | off;
    Default:    expires off;
    Context:    http, server, location, if in location
    #配置过期时间
    [root@web01 ~]# vim /etc/nginx/conf.d/cacha.conf 
    server {
        listen 80;
        server_name linux.cache.com;
        root /code/cache;
        location ~* .(jpg|png|gif)$ {
            root /code/cache;
            expires 7d;
        }
    }


    4)配置不走缓存

    #公司测试化境经常更新前端代码,需要关闭缓存
    1.使用无痕模式
    2.开启浏览器 Disable cache
    3.配置nginx
        location ~* .(jpg|png|gif)$ {
            root /code/cache;
            add_header Cache-Control no-cache;
            etag off;
            if_modified_since off;
        }



    2.静态资源读取

    1)文件高速读取

    Syntax: sendfile on | off;
    Default: sendfile off;
    Context: http, server, location, if in location

    2)高效传输(开启了sendfile)

    Syntax: tcp_nopush on | off;
    Default: tcp_nopush off;
    Context: http, server, location

    3)长连接传输(必须开启长连接)

    Syntax: tcp_nodelay on | off;
    Default: tcp_nodelay on;
    Context: http, server, location

    4)注意

    tcp_nodelay和tcp_nopush只能配置一个,不能同时配置

    3.静态资源压缩

    1)静态资源压缩语法

    #开启压缩
    Syntax: gzip on | off;
    Default: gzip off;
    Context: http, server, location, if in location

    #指定压缩类型
    Syntax: gzip_types mime-type ...;
    Default: gzip_types text/html;
    Context: http, server, location

    #指定压缩比例
    Syntax: gzip_comp_level level;
    Default: gzip_comp_level 3-5; #1-9个级别
    Context: http, server, location

    #指定传输协议
    Syntax: gzip_http_version 1.0 | 1.1;
    Default: gzip_http_version 1.1;
    Context: http, server, location

    2)压缩配置

    [root@web01 /code/cache]# vim /etc/nginx/conf.d/gzip.conf 
    server {
        listen 80;
        server_name linux.gzip.com;
        root /code/cache;
        location ~* .(jpg|png|gif)$ {
            gzip on;
            gzip_types image/jpeg image/gif image/png;
            gzip_comp_level 9;
        }
        location ~* .(txt|css)$ {
            gzip on;
            gzip_types text/css text/plain;
            gzip_comp_level 5;
        }
    }



    4.防资源盗链

    1)配置被盗链的网站

    [root@web02 /etc/nginx/conf.d]# vim beidaolian.conf
    server {
    listen 80;
    server_name linux.beidaolian.com;

    location / {
    root /code/beidaolian;
    index index.html;
    }
    }

    [root@web02 /etc/nginx/conf.d]# mkdir /code/beidaolian
    [root@web02 /etc/nginx/conf.d]# cd /code/beidaolian/
    [root@web02 /code/beidaolian]# rz
    [root@web02 /code/beidaolian]# ll
    total 13444
    -rw-r--r-- 1 root root 18632 2020-09-11 15:57 1.jpg
    -rw-r--r-- 1 root root 471421 2020-09-11 15:57 3.jpg

    2)配置盗链的网站

    [root@web01 /]# vim /etc/nginx/conf.d/daolian.conf
    server {
    listen 80;
    server_name linux.daolian.com;
    root /code/cache;
    }

    [root@web01 /]# vim /code/cache/index.html
    <img src="http://linux.beidaolian.com/1.jpg" />

    #配置hosts
    [root@web01 /]# vim /etc/hosts
    10.0.0.8 linux.beidaolian.com

    #windows配置访问页面
    10.0.0.7 linux.daolian.com
    访问http://linux.daolian.com/

    3)配置防盗链语法

    Syntax: valid_referers none | blocked | server_names | string ...;
    Default: —
    Context: server, location

    none #nginx日志中referer部分为空
    blocked #nginx日志中referer部分没有携带协议,没有http或者https
    server_names #nginx日志中referer部分为指定的域名

    4)防盗链配置

    [root@web02 /code/beidaolian]# cat /etc/nginx/conf.d/beidaolian.conf
    server {
    listen 80;
    server_name linux.beidaolian.com;

    location / {
    root /code/beidaolian;
    index index.html;
    }

    location ~* .jpg$ {
    root /code/beidaolian;
    #valid_referers none blocked server_name linux.beidaolian.com *.baidu.com;
    valid_referers none blocked linux.beidaolian.com;
    if ($invalid_referer) {
    return 403;
    }
    }
    }

    5)伪造referer请求头

    [root@web01 ~]# curl -e "http://linux.daolian.com" -I linux.beidaolian.com/1.jpg
    HTTP/1.1 500 Internal Server Error
    Server: nginx/1.18.0
    Date: Fri, 11 Sep 2020 08:23:52 GMT
    Content-Type: text/html
    Content-Length: 177
    Connection: close

    [root@web01 ~]# curl -e "http://linux.beidaolian.com" -I linux.beidaolian.com/1.jpg
    HTTP/1.1 200 OK
    Server: nginx/1.18.0
    Date: Fri, 11 Sep 2020 08:24:19 GMT
    Content-Type: image/jpeg
    Content-Length: 18632
    Last-Modified: Fri, 11 Sep 2020 07:57:48 GMT
    Connection: keep-alive
    ETag: "5f5b2dfc-48c8"
    Accept-Ranges: bytes

    5.允许跨域访问

    #盗链就是由我的网站向你的网站发起get获取资源的请求

    #跨域访问由我的网站向你的网站发起http的链接请求

    1)配置被跨域的网站

    [root@web02 /etc/nginx/conf.d]# vim beikuayu.conf
    server {
        listen 80;
        server_name linux.beikuayu.com;
        location / {
            root /code/beikuayu;
            index index.html;
        }
    }
    #创建站点
    [root@web02 ~]# echo "bei kua yu de wang zhan" > /code/beikuayu/index.html

    2)配置跨域的网站

    [root@web01 ~]# vim /etc/nginx/conf.d/kuayu.conf
    server {
    listen 80;
    server_name linux.kuayu.com;

    location / {
    root /code/kuayu;
    index index.html;
    }
    }

    #配置站点
    [root@web01 ~]# mkdir /code/kuayu
    [root@web01 ~]# vim /code/kuayu/index.html
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>测试ajax和跨域访问</title>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    </head>
    <script type="text/javascript">
    $(document).ready(function(){
    $.ajax({
    type: "GET",
    url: "http://linux.beikuayu.com",
    success: function(data) {
    alert("sucess 卧槽 卧槽 卧槽 成功了!!!");
    },
    error: function() {
    alert("fail!!,跨不过去啊,不让进去啊,只能蹭蹭!");
    }
    });
    });
    </script>
    <body>
    <h1>测试跨域访问</h1>
    </body>
    </html>

    3)配置hosts

    [root@web01 ~]# vim /etc/hosts
    10.0.0.7 linux.beikuayu.com
    10.0.0.8 linux.beikuayu.com
    [root@web02 ~]# vim /etc/hosts
    10.0.0.7 linux.beikuayu.com
    10.0.0.8 linux.beikuayu.com
    #配置windows的hosts
    10.0.0.7 linux.kuayu.com


    4)配置允许跨域访问

    [root@web02 /etc/nginx/conf.d]# vim beikuayu.conf 
    server {
        listen 80;
        server_name linux.beikuayu.com;
        root /code/beikuayu;
        index index.html;
        location ~* .html$ {
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
        }
    }


    cpu亲和

    1.查看cpu状态

    #添加服务器核心数为4个
    [root@web02 ~]# lscpu
    CPU(s): 4
    On-line CPU(s) list: 0-3
    NUMA node0 CPU(s): 0-3

    2.配置nginx

    [root@web02 ~]# vim /etc/nginx/nginx.conf 
    user www;
    worker_processes 4;

    [root@web02 ~]# systemctl restart nginx

    3.查看进程绑定的cpu

    [root@web02 ~]# ps -eo pid,args,psr | grep [n]ginx
    6864 nginx: master process /usr/ 1
    6865 nginx: worker process 3
    6866 nginx: worker process 2
    6867 nginx: worker process 3
    6868 nginx: worker process 2

    4.配置cpu亲和

    1)方式一

    worker_processes 16; 
    worker_cpu_affinity 0000000000000001 0000000000000010 0000000000000100 0000000000001000 0000000000010000 0000000000100000 
    0000000001000000 0000000010000000 0000000100000000 0000001000000000 0000010000000000 0000100000000000 0001000000000000 0010000000000000 0100000000000000 1000000000000000;

    2)方式二

    worker_processes 2; 
    #worker_cpu_affinity 01 10;
    #worker_cpu_affinity 0101 1010;
    worker_cpu_affinity 010101 101010;

    3)方式三

    worker_processes auto; 
    worker_cpu_affinity auto;

    4)配置完cpu亲和查看进程绑定

    [root@web02 ~]# ps -eo pid,args,psr | grep [n]ginx
    7024 nginx: master process /usr/ 1
    7025 nginx: worker process 0
    7026 nginx: worker process 1
    7027 nginx: worker process 2
    7028 nginx: worker process 3



    nginx优化部分完整配置文件

    [root@nginx ~]# cat nginx.conf
    user www;     #启动用户
    worker_processes auto;  
    worker_cpu_affinity auto;
    error_log /var/log/nginx/error.log warn;  #错误日志  警告级别
    pid /run/nginx.pid;    #pid文件  
    worker_rlimit_nofile 35535;    #配置Nginx worker进程最大打开文件数
    events 
        use epoll;
        worker_connections 10240;   #单个进程允许的客户端最大连接数 10240
    }
    http {
        include             mime.types;
        default_type        application/octet-stream;
        charset utf-8;     #识别中文
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';
                          
           
      $remote_addr :访问用户的IP  从哪个IP进入我的网站
      $remote_user :登录的用户
      $time_local] :本地时间
      $request     :请求(什么类型的请求)
      $status      :状态(200,404,)对应状态码
      $body_bytes_sent    :请求的页面有多大  多少字节
      $http_referer:上一个页面是谁
      $http_user_agent  :访问的客户端
      $http_x_forwarded_for:真实IP
        access_log  /var/log/nginx/access.log  main;   #访问日志的完整的路径记录
        server_tokens off;
        client_max_body_size 200m;     
        sendfile            on;
        tcp_nopush          on;
        tcp_nodelay         on;
        keepalive_timeout   65;
        gzip on;
        gzip_disable "MSIE [1-6].";
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_buffers 16 8k;
        gzip_min_length 1024;
        gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript image/jpeg;
        include /etc/nginx/conf.d/*.conf;
    }

     

     

    nginx优化总结

    1、CPU亲和、worker进程数、调整nginx进程打开的文件句柄数
    2、使用Epool网络模型、调整每个worker进程的最大连接数
    3、文件的高效读取sendfile、nopush
    4、文件的传输实时性、nodealy
    5、开启tcp长连接,以及长连接超时时间keepalive_timeout
    6、开启文件传输压缩gzip
    7、开启静态文件expires缓存
    8、隐藏nginx版本号
    9、禁止通过ip地址访问,禁止恶意域名解析,只允许域名访问
    10、配置防盗链、以及跨域访问
    11、防DDOS、cc攻击,限制单IP并发连接,以及http请求
    12、优雅显示nginx错误页面
    13、nginx加密传输https优化
    14、nginx proxy_cache、fastcgi_cache、uwsgi_cache 代理缓存,第三方工具(squid、varnish)

     



  • 相关阅读:
    MyBatis框架(一)
    开始约定编程——Spring AOP
    Spring Boot快速入门
    全注解下的Spring IoC
    Java泛型
    Java异常
    windows监控web程序连接数
    winform导出excel报'object' does not contain a definition for 'get_Range'的问题
    git基本操作
    .net core中使用HttpClient碰到的问题:This instance has already started one or more requests. Properties can only be modified before sending the first request
  • 原文地址:https://www.cnblogs.com/wzj-qwerty/p/13906818.html
Copyright © 2020-2023  润新知