ToB企服应用市场:ToB评测及商务社交产业平台

标题: Nginx 配置和性能调优 [打印本页]

作者: 用户云卷云舒    时间: 2022-6-23 10:47
标题: Nginx 配置和性能调优
优化 Nginx worker 进程数

Nginx 有 master 和 worker 两种进程,master 进程用于管理 worker 进程,worker 进程用于 Nginx 服务。
worker 进程数默认为 1 。
  1. worker_processes  1;
复制代码
worker 进程数应该设置为服务器 CPU 的核数。
  1. [root@localhost ~]# grep -c processor /proc/cpuinfo         # 查看CPU核数
  2. 2
  3. [root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf    # 设置worker进程数
  4. worker_processes  2;
复制代码
worker_processes 这个参数最好是设置成 auto 自动匹配进程数。
绑定 Nginx 进程到不同的 CPU 上

默认情况下,Nginx 的多个进程有可能跑在某一个 CPU 或 CPU 的某一核上,导致 Nginx 进程使用硬件的资源不均,因此绑定 Nginx 进程到不同的 CPU 上是为了充分利用硬件的多 CPU 多核资源。
  1. [root@localhost ~]# grep -c processor /proc/cpuinfo    # 查看CPU核数
  2. 2
  3. worker_processes  2;         # 2核CPU的配置
  4. worker_cpu_affinity 01 10;
  5. worker_processes  4;         # 4核CPU的配置
  6. worker_cpu_affinity 0001 0010 0100 1000;   
  7. worker_processes  8;         # 8核CPU的配置
  8. worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 1000000;
复制代码
优化 Nginx 单个进程允许的最大连接数

控制 Nginx 单个进程允许的最大连接数的参数为 worker_connections ,这个参数要根据服务器性能和内存使用量来调整。
进程的最大连接数受 Linux 系统进程打开的最大文件数的限制,只有执行了 “ulimit -HSn 65535” 之后,worker_connections 才能生效。
连接数包括代理服务器的连接、客户端的连接等,Nginx 总并发连接数 = worker_processes * worker_connections。总数保持在 3w 左右即可。
  1. worker_processes  2;
  2. worker_cpu_affinity 01 10;
  3. user nginx nginx;
  4. events {
  5.     use epoll;
  6.     worker_connections  15000;
  7. }
复制代码
优化 Nginx worker 进程打开的最大文件数

  1. worker_rlimit_nofile 65535;    # worker 进程打开的最大文件数,可设置为优化后的 ulimit -HSn 的结果
复制代码
开启高效文件传输模式

sendfile 参数用于开启文件的高效传输模式,该参数实际上是激活了 sendfile() 功能。
sendfile() 是作用于两个文件描述符之间的数据拷贝函数,这个拷贝操作是在内核之中的,被称为 “零拷贝” 。sendfile 比 read 和 write 函数要高效得多,因为 read 和 write 函数要把数据拷贝到应用层再进行操作。
tcp_nopush 参数用于激活 Linux 上的 TCP_CORK socket 选项,此选项仅仅当开启 sendfile 时才生效,tcp_nopush 参数可以把 http response header 和文件的开始部分放在一个文件里发布,以减少网络报文段的数量。
  1. http {
  2.    include       mime.types;
  3.    default_type  application/octet-stream;
  4.    sendfile      on;    # 开启文件的高效传输模式
  5.    tcp_nopush    on;    # 激活 TCP_CORK socket 选择
  6.    tcp_nodelay   on;    # 数据在传输的过程中不进缓存
  7.    keepalive_timeout  65;
  8.    include vhosts/*.conf;
  9. }
复制代码
优化 Nginx 连接的超时时间

连接超时的作用


连接超时存在的问题


设置超时时间


  1. http {
  2.     include       mime.types;
  3.     server_names_hash_bucket_size  512;   
  4.     default_type  application/octet-stream;
  5.     sendfile        on;
  6.     tcp_nodelay     on;
  7.     keepalive_timeout  65;
  8.     client_header_timeout 15;
  9.     client_body_timeout 15;
  10.     send_timeout 25;
  11.     include vhosts/*.conf;
  12. }
复制代码
限制上传文件的大小

client_max_body_size 用于设置最大的允许客户端请求主体的大小。
在请求头中有 “Content-Length” ,如果超过了此配置项,客户端会收到 413 错误,即请求的条目过大。
  1. http {
  2.     client_max_body_size 8m;    # 设置客户端最大的请求主体大小为 8 M
  3. }
复制代码
FastCGI 相关参数调优

当 LNMP 组合工作时,用户通过浏览器输入域名请求 Nginx Web 服务:

这就是 LNMP 环境的基本请求流程。
在 Linux 中,FastCGI 接口即为 socket ,这个 socket 可以是文件 socket,也可以是 IP socket。
  1. http {
  2.     include       mime.types;
  3.     default_type  application/octet-stream;
  4.     sendfile        on;
  5.     keepalive_timeout  65;
  6.     fastcgi_connect_timeout  240;    # Nginx服务器和后端FastCGI服务器连接的超时时间
  7.     fastcgi_send_timeout     240;    # Nginx允许FastCGI服务器返回数据的超时时间,即在规定时间内后端服务器必须传完所有的数据,否则Nginx将断开这个连接
  8.     fastcgi_read_timeout     240;    # Nginx从FastCGI服务器读取响应信息的超时时间,表示连接建立成功后,Nginx等待后端服务器的响应时间
  9.     fastcgi_buffer_size      64k;    # Nginx FastCGI 的缓冲区大小,用来读取从FastCGI服务器端收到的第一部分响应信息的缓冲区大小
  10.     fastcgi_buffers        4 64k;    # 设定用来读取从FastCGI服务器端收到的响应信息的缓冲区大小和缓冲区数量
  11.     fastcgi_busy_buffers_size    128k;    # 用于设置系统很忙时可以使用的 proxy_buffers 大小
  12.     fastcgi_temp_file_write_size 128k;    # FastCGI 临时文件的大小
  13. #   fastcti_temp_path            /data/ngx_fcgi_tmp;    # FastCGI 临时文件的存放路径
  14.     fastcgi_cache_path           /data/ngx_fcgi_cache  levels=2:2  keys_zone=ngx_fcgi_cache:512m  inactive=1d  max_size=40g;    # 缓存目录
  15.     server {
  16.         listen       80;
  17.         server_name  www.abc.com;
  18.         location / {
  19.             root   html/www;
  20.             index  index.html index.htm;
  21.         }
  22.         location ~ .*\.(php|php5)?$ {
  23.             root            html/www;
  24.             fastcgi_pass    127.0.0.1:9000;
  25.             fastcgi_index   index.php;
  26.             include         fastcgi.conf;
  27.             fastcgi_cache   ngx_fcgi_cache;            # 缓存FastCGI生成的内容,比如PHP生成的动态内容
  28.             fastcgi_cache_valid      200  302  1h;     # 指定http状态码的缓存时间,这里表示将200和302缓存1小时
  29.             fastcgi_cache_valid      301  1d;          # 指定http状态码的缓存时间,这里表示将301缓存1天
  30.             fastcgi_cache_valid      any  1m;          # 指定http状态码的缓存时间,这里表示将其他状态码缓存1分钟
  31.             fastcgi_cache_min_uses   1;                # 设置请求几次之后响应被缓存,1表示一次即被缓存
  32.             fastcgi_cache_use_stale  error  timeout  invalid_header  http_500;    # 定义在哪些情况下使用过期缓存
  33.             fastcgi_cache_key        http://$host$request_uri;                    # 定义 fastcgi_cache 的 key
  34.         }
  35.     }
  36. }
复制代码
gzip 压缩

Nginx gzip 压缩模块提供了压缩文件内容的功能,用户请求的内容在发送到客户端之前,Nginx 服务器会根据一些具体的策略实施压缩,以节约网站出口带宽,同时加快数据传输效率,来提升用户访问体验。
需要压缩的对象有 html 、js 、css 、xml 、shtml ,图片和视频尽量不要压缩,因为这些文件大多都是已经压缩过的,如果再压缩可能反而变大。
另外,压缩的对象必须大于 1KB,由于压缩算法的特殊原因,极小的文件压缩后可能反而变大。
  1. http {
  2.     gzip  on;                    # 开启压缩功能
  3.     gzip_min_length  1k;         # 允许压缩的对象的最小字节
  4.     gzip_buffers  4 32k;         # 压缩缓冲区大小,表示申请4个单位为32k的内存作为压缩结果的缓存
  5.     gzip_http_version  1.1;      # 压缩版本,用于设置识别HTTP协议版本
  6.     gzip_comp_level  9;          # 压缩级别,1级压缩比最小但处理速度最快,9级压缩比最高但处理速度最慢
  7.     gzip_types  text/plain application/x-javascript text/css application/xml;    # 允许压缩的媒体类型
  8.     gzip_vary  on;               # 该选项可以让前端的缓存服务器缓存经过gzip压缩的页面,例如用代理服务器缓存经过Nginx压缩的数据
  9. }
复制代码
配置 expires 缓存期限

Nginx expires 的功能就是给用户访问的静态内容设定一个过期时间。
当用户第一次访问这些内容时,会把这些内容存储在用户浏览器本地,这样用户第二次及以后继续访问该网站时,浏览器会检查加载已经缓存在用户浏览器本地的内容,就不会去服务器下载了,直到缓存的内容过期或被清除。
不希望被缓存的内容:广告图片、网站流量统计工具、更新很频繁的文件。
缓存期限参考:新浪缓存 15 天,京东缓存 25 年,淘宝缓存 10 年。
  1. server {
  2.     listen       80;
  3.     server_name  www.abc.com abc.com;
  4.     root    html/www;
  5.     location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$    # 缓存的对象
  6.     {
  7.         expires 3650d;     # 缓存期限为 10 年
  8.     }
  9. }
复制代码
配置防盗链

什么是防盗链?
简单地说,就是其它网站未经许可,通过在其自身网站程序里非法调用其他网站的资源,然后在自己的网站上显示这些调用的资源,使得被盗链的那一端消耗带宽资源 。
通过 HTTP referer 实现防盗链。
  1. #第一种,匹配后缀
  2. location ~ .*\.(gif|jpg|jpeg|png|bm|swf|flv|rar|zip|gz|bz2)$ {    # 指定需要使用防盗链的媒体资源
  3.     access_log  off;                                              # 不记录日志
  4.     expires  15d;                                                 # 设置缓存时间
  5.    valid_referers  none  blocked  *.test.com  *.abc.com;         # 表示仅允许这些域名访问上面的媒体资源
  6.     if ($invalid_referer) {                                       # 如果域名不是上面指定的地址就返回403
  7.        return 403
  8.     }
  9. }
  10. #第二种,绑定目录
  11. location /images {  
  12.     root /web/www/img;
  13.     vaild_referers none blocked *.spdir.com *.spdir.top;
  14.     if ($invalid_referer) {
  15.         return 403;
  16.     }
  17. }
复制代码
server 代码块

server 代码块位于 http 代码块内部,每一个 server 都可以用来配置一个虚拟主机。也就是说,每一个 server 代表了一个虚拟服务器的配置信息。
可以添加多个 server 来配置多个虚拟主机。
  1. server {
  2.     listen       80;
  3.     server_name  localhost;
  4.     #access_log  logs/host.access.log  main;
  5.     root   "D:/phpStudy/WWW";
  6.     location / {
  7.        index  index.html index.htm index.php l.php;
  8.        autoindex  off;
  9.     }
  10.     #error_page  404              /404.html;
  11.     # redirect server error pages to the static page /50x.html
  12.     #
  13.     error_page   500 502 503 504  /50x.html;
  14.     location = /50x.html {
  15.         root   html;
  16.     }
  17.     # proxy the PHP scripts to Apache listening on 127.0.0.1:80
  18.     #
  19.     #location ~ \.php$ {
  20.     #    proxy_pass   http://127.0.0.1;
  21.     #}
  22.     # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  23.     #
  24.     location ~ \.php(.*)$  {
  25.         fastcgi_pass   127.0.0.1:9000;
  26.         fastcgi_index  index.php;
  27.         fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
  28.         fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
  29.         fastcgi_param  PATH_INFO  $fastcgi_path_info;
  30.         fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
  31.         include        fastcgi_params;
  32.     }
  33.     # deny access to .htaccess files, if Apache's document root
  34.     # concurs with nginx's one
  35.     #
  36.     #location ~ /\.ht {
  37.     #    deny  all;
  38.     #}
  39. }
复制代码
server 中的主要配置有:

location 代码块

location 代码块位于 server 代码块内部。
location 用于配置虚拟主机的 URI,它是一个非常重要的配置。
可以给每一个 server(虚拟主机)配置多个 location。
可以根据不同的 URI 配置不同的 location,来处理不同的请求。
location 的语法格式

  1. location [ = | ~ | ~* | ^~ | @] uri {...}
复制代码
其中, = | ~ | ~* | ^~ | @ 表示前缀,也叫修饰符,是可选的;uri 表示普通字符串或正则表达式,是必须的。

如果 location 中使用了修饰符 ~ 或者 ~*,那么,这个 location 就是正则 location;否则,就是字符串 location。
多个 location 的匹配顺序

多个 location 的匹配顺序与 location 的位置顺序没有直接关系,匹配顺序为:
注意: 虽然字符串 location 的优先级高于正则 location。但是,如果匹配成功的字符串 location 中没有使用修饰符 ^~ ,也不是精准匹配,那么还会继续检测是否有匹配的正则 location。如果匹配到了正则 location,就立即使用该正则 location 并停止匹配;否则,才会使用字符串 location。
也就是说,匹配到的字符串 location 可能会被正则 location 所覆盖。
匹配成功的字符串 location,如果不想再继续检测匹配正则 location,有三种实现方式:

匹配模式及其顺序

说明:对于字符串 location,如果没有 = 修饰符,就都是前缀匹配;而正则 location,可能是前缀匹配、后缀匹配、中间匹配和完整匹配中的任意一种,这取决于正则表达式本身。
配置默认主页

  1. location / {
  2.     index   index.html index.htm index.php l.php;
  3.     autoindex  off;
  4. }
复制代码
配置反向代理

  1. location / {
  2.     proxy_pass http://localhost:8888;
  3.     proxy_set_header Host $host;
  4.     proxy_set_header X-Real-IP $remote_addr;
  5.     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  6. }
复制代码
URL 美化(省略 index.php 入口文件)

  1. location / {
  2.     try_files $uri $uri/ /index.php?$query_string;
  3. }
复制代码
upstream 代码块

upstream 代码块位于 http 代码块内部。
upstream 用于对服务器集群进行负载均衡的配置。
  1. upstream name {
  2.     ip_hash;
  3.     server 192.168.1.100:8000;
  4.     server 192.168.1.100:8001 down;
  5.     server 192.168.1.100:8002 max_fails=3;
  6.     server 192.168.1.100:8003 fail_timeout=20s;
  7.     server 192.168.1.100:8004 max_fails=3 fail_timeout=20s;
  8. }
复制代码

配置文件中的全局变量


源码附件已经打包好上传到百度云了,大家自行下载即可~
   链接: https://pan.baidu.com/s/14G-bpVthImHD4eosZUNSFA?pwd=yu27
提取码: yu27
百度云链接不稳定,随时可能会失效,大家抓紧保存哈。
  如果百度云链接失效了的话,请留言告诉我,我看到后会及时更新~
开源地址
码云地址:
http://github.crmeb.net/u/defu
Github 地址:
http://github.crmeb.net/u/defu

来源:https://blog.csdn.net/CRMEB/article/details/125294828
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4