Nginx优化

1.ab压力测试工具(Web服务器、API接口的测量请求/秒、响应时间、吞吐量)
以防患业务量突增带来的接口压力,评估好系统压力,使用工具检测当前系统情况,是否能满足对应压力的需求。
ab命令 # 属于httpd-tools
[root@LNMP ~]# ab -n 200 -c 2 http://127.0.0.1/
-n 要执行的请求数 -c 请求的并发数 -k 是否开启长连接

2.系统性能优化(增大文件描述符)
[root@LNMP ~]# tail -1 /etc/security/limits.conf

点击查看代码
···
* - nofile 65535
···
为什么我们要关注这个高并发短连接呢?

有两个方面需要注意:
1) 高并发可以让服务器在短时间范围内同时占用大量端口,而端口有个0~65535的范围,并不是很多,刨除系统和其他服务要用的,剩下的就更少了。
2)在这个场景中,短连接表示业务处理+传输数据的时间 远远小于 TIMEWAIT超时的时间的连接。

3.代理服务器优化(负载均衡、PHP)[长连接减少握手次数,降低服务器损耗]
1)负载均衡优化

点击查看代码
upstream http_backend {
    server 127.0.0.1:8080;
    keepalive 16;   #负载均衡和后端长连接
}

server {
    ...
    location /http/ {
        proxy_pass http://http_backend;
        proxy_http_version 1.1;         #对于http协议应该指定为1.1
        proxy_set_header Connection ""; #清除“connection”头字段
        proxy_next_upstream error timeout http_500 http_502 http_503 http_504;  #平滑过渡
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwared-For $proxy_add_x_forwarded_for;
        proxy_connect_timeout 30s;      # 代理连接web超时时间
        proxy_read_timeout 60s;         # 代理等待web响应超时时间
        proxy_send_timeout 60s;         # web回传数据至代理超时时间
        proxy_buffering on;             # 开启代理缓冲区,web回传数据至缓冲区,代理边收边传返回给客户端
        proxy_buffer_size 32k;          # 代理接收web响应的头信息的缓冲区大小
        proxy_buffers 4 128k;           # 缓冲代理接收单个长连接内包含的web响应的数量和大小
    ...
    }
}

2)PHP优化
点击查看代码
upstream fastcgi_backend {
    server 127.0.0.1:9000;
    keepalive 8;
}

server {
    ...
    location /fastcgi/ {
        fastcgi_pass fastcgi_backend;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_keep_conn on;   		# 开启长连接(提高并发)
        fastcgi_connect_timeout 60s;	# 超时时间
        include fastcgi_params;
        ...
    }
}

4.静态资源优化[定时清理静态资源缓存]
1)静态资源缓存7天

点击查看代码
server {
	listen 80;
	server_name www.oldboy.com;
	root /code/test;
	index index.html;
    location ~ .*\.(jpg|gif|png)$ {
        expires      7d;    #缓存
    }
}
2)静态资源不存储,不缓存
点击查看代码
server {
        listen 80;
        server_name www.oldboy.com;
        root /code/test;
        index index.html;

        location ~ .*\.(js|css|html)$ {
        add_header Cache-Control no-store;  #不存储
        add_header Pragma no-cache;			#不缓存
        }

        location ~ .*\.(jpg|gif|png)$ {
        expires      7d;
        }
}

5.文件高效传输(只到内核态,不经过用户态)[提高文件传输速率]
配置在nginx主配置文件或业务配置文件中

场景 推荐配置 说明
静态文件下载 tcp_nopush on 大文件传输,需要高吞吐
API接口 tcp_nopush off 小数据包,需要低延迟
混合场景 tcp_nopush on + tcp_nodelay on 通用配置
代理服务器 tcp_nopush on 提高后端通信效率

6.静态资源压缩[节约带宽,提高响应速度]

点击查看代码
级别	CPU消耗	    压缩率	适用场景	示例格式压缩率
1	★	    ~20%	实时流媒体	   JS: 65% → 52%
3	★★	   ~35%	   动态内容	       HTML: 70% → 45%
6	★★★	  ~50%	  通用Web	        CSS: 80% → 40%
9	★★★★ ~55%	  静态资源	      JSON: 75% → 35%
注:压缩率基于典型文本内容测试,实际结果取决于内容冗余度


gzip传输压缩,传输前压缩,传输后解压
语法格式: gzip on | off;
默认值: gzip off;
放置位置: http, server, location, if in location

gzip压缩哪些文件
语法格式: gzip_types mime-type ...;
默认值: gzip_types text/html;
放置位置: http, server, location

gzip压缩比率,加快传输,但压缩本身比较耗费服务器性能
语法格式: gzip_comp_level level;
默认值:gzip_comp_level level 1;
放置位置: http, server, location


gzip压缩协议版本,压缩使用在http哪个协议,主流选择1.1版本
语法格式: gzip_http_version 1.0 | 1.1;
默认值:gzip_http_version 1.1;
放置位置: http, server, location

7.防止资源盗链[防止资源被其他网站恶意盗用]

点击查看代码
Syntax: valid_referers none | blocked | server_name |
#none: referer来源头部为空的情况
#blocked: referer来源头部不为空,这些都不以http://或者https://开头
#server_name: 来源头部信息包含当前域名,可以正则匹配

8.跨域访问

点击查看代码
server {
	listen 80;
	server_name www.wq.com;
	root /code/test;
	index index.html;
	 location ~ .*\.(html|htm)$ {  
            add_header Access-Control-Allow-Origin *;		#允许所有跨域
            add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;       
        }
}

9.CPU亲和[减少进程之间不断频繁切换,减少性能损耗]

点击查看代码
[root@LNMP ~]# vim /etc/nginx/nginx.conf
user  nginx;
worker_processes  auto;
worker_cpu_affinity auto;   # 配置CPU自动亲和

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;
....

[root@LNMP ~]# ps -eo pid,args,psr|grep [n]ginx  #查看CPU亲和    

10.nginx通用优化配置

点击查看代码
[root@LNMP~]# vim /etc/nginx/nginx.conf
user www;                   # nginx进程启动用户
worker_processes auto;      #与cpu核心一致即可
worker_cpu_affinity auto;   # cpu亲和

error_log /var/log/nginx/error.log warn;    # 错误日志
pid /run/nginx.pid;
worker_rlimit_nofile 35535;  #每个work能打开的文件描述符,调整至1w以上,负荷较高建议2-3w 不用

events {
    use epoll;                  # 使用epoll高效网络模型 默认的
    worker_connections 65535;   # 限制每个进程能处理多少个连接,10240x[cpu核心]
}

http {
    include             mime.types;
    default_type        application/octet-stream;
    charset utf-8,gbk;      # 统一使用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"';

    #定义json日志格式              
    log_format json_access '{"@timestamp":"$time_iso8601",'
                      '"host":"$server_addr",'
                      '"clientip":"$remote_addr",'
                      '"size":$body_bytes_sent,'
                      '"responsetime":$request_time,'
                      '"upstreamtime":"$upstream_response_time",'
                      '"upstreamhost":"$upstream_addr",'
                      '"http_host":"$host",'
                      '"url":"$uri",'
                      '"domain":"$host",'
                      '"xff":"$http_x_forwarded_for",'
                      '"referer":"$http_referer",'
                      '"status":"$status"}';

    access_log  /var/log/nginx/access.log  main;    # 访问日志

    server_tokens off;          # 禁止浏览器显示nginx版本号
    client_max_body_size 20m;  # 文件上传大小限制调整 默认1M

    # 文件高效传输,静态资源服务器建议打开
    sendfile            on;
    tcp_nopush          on;
    # 文件实时传输,动态资源服务建议打开,需要打开keepalive
    tcp_nodelay         on;
    keepalive_timeout   65;

    # Gzip 压缩
    gzip on;
    gzip_disable "MSIE [1-6]\.";    #针对IE浏览器不进行压缩
    gzip_http_version 1.1;
    gzip_comp_level 2;      #压缩级别
    gzip_buffers 16 8k;     #压缩的缓冲区
    gzip_min_length 1024;   #文件大于1024字节才进行压缩,默认值20
    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;
}

posted on 2025-12-12 09:40    阅读(3)  评论(0)    收藏  举报