侧边栏壁纸
博主头像
SRE实战博主等级

行动起来,活在当下

  • 累计撰写 9 篇文章
  • 累计创建 1 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Nginx部署与优化

Miracle
2024-03-01 / 0 评论 / 0 点赞 / 19 阅读 / 12331 字

安装nginx

yum源直接安装

yum install nginx -y

源码编译安装

#nginx源码包下载官网地址:http://nginx.org/en/download.html 
#此处以新版本nginx-1.17.7.tar.gz为例,注意该版本不仅支持http七层代理,还支持tcp四层代理。  
#下载源码包并解压包  
wget  
tar zxvf nginx-1.17.7.tar.gzcd nginx-1.17.7
#安装编译环境  
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
#编译安装nginx
./configure --prefix=/usr/local/nginx-1.17 \
--with-http_ssl_module --with-http_stub_status_module \
--with-http_realip_module  --with-threads
make && make install

如果需要其他模块,请自行添加其它模块参数,官网地址:http://nginx.org/en/docs/configure.html。

配置文件构成

...              #全局块events {         #events块
   ...}http      #http块{
    ...   #http全局块
    server        #server块
    { 
        ...       #server全局块
        location [PATTERN]   #location块
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局块}

全局块配置调优

#nginx进程数,建议按照cpu数目来指定,一般跟cpu核数相同或为它的倍数。
worker_processes 8;
#为每个进程分配cpu,上例中将8个进程分配到8个cpu,当然可以写多个,或者将一个进程分配到多个cpu。
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
#收到新连接通知后接受尽可能多的连接,作用于eventmulti_accept on;
#Nginx最多可以打开文件数,与ulimit -n保持一致,如:worker_rlimit_nofile 65535;
worker_rlimit_nofile 65535;

event段调优配置

events {
  #作用于event的I/O多路复用模型  
  use epoll;#是单个worker进程允许客户端最大连接数,这个数值一般根据服务器性能和内存来制
  worker_connections 65535;#收到新连接通知后接受尽可能多的连接,作用于event
  multi_accept on;}

http全局段调优

http {
include mime.types;
default_type application/octet-stream;
……
sendfile on;
tcp_nopush on;
……

#sendfile:开启高效文件传输模式,sendfile指定nginx是否调用sendfile
#函数来输出文件对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载
#应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。
#tcp_nopush:必须在sendfile开启模式才有效,防止网路阻塞,积极的减少网络报文段的数量
#tcp_nodelay:

连接超时时间

主要目的是保护服务器资源,CPU,内存,控制连接数,因为建立连接也是需要消耗资源的,如:

keepalive_timeout 60;
keepalive_requests 10240;
tcp_nodelay on;
client_header_buffer_size 4k;
open_file_cache max=102400 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
client_header_timeout 15;
client_body_timeout 15;
reset_timedout_connection on;
send_timeout 15;
server_tokens off;
client_max_body_size 500m;
proxy_connect_timeout 30s;
proxy_send_timeout 120s;
proxy_read_timeout 120s;

#keepalived_timeout 60:客户端连接保持会话超时时间,超过这个时间,服务器断开这个链接 
#keepalive_requests 10240:参数限制了一个 HTTP 长连接最多可以处理完成的最大请求数, 默
#认是 100。当连接处理完成的请求数达到最大请求数后,将关闭连接。  
#tcp_nodelay:也是防止网络阻塞,不过要包涵在keepalived参数才有效client_header_buffer_size
4k:客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超
#过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf 
#PAGESIZE取得。open_file_cache max=102400 #inactive=20s:这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致
#inactive是指经过多长时间文件没被请求后删除缓存。 
#open_file_cache_valid 30s:这个是指多长时间检查一次缓存的有效信息。 
#open_file_cache_min_uses 1:open_file_cache指令中的inactive 参数时间内文件的最少使用次数
#如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive时间内一次没被使用,它将被移除。  
#client_header_timeout:设置请求头的超时时间。我们也可以把这个设置低些,如果超过这个时间没有发送任何数据
#nginx将返回request time out的错误  
#client_body_timeout:设置请求体的超时时间。我们也可以把这个设置低些,超过这个时间没有发送任何数据,和上面一样的错误提示  
#reset_timeout_connection:告诉nginx关闭不响应的客户端连接。这将会释放那个客户端所占有的内存空间。  
#send_timeout:响应客户端超时时间,这个超时时间仅限于两个活动之间的时间,如果超过这个时间,客户端没有任何活动,nginx关闭连接
#server_tokens:并不会让nginx执行的速度更快,但它可以关闭在错误页面中的nginx版本数字,这样对于安全性是有好处的。  
#client_max_body_size:上传文件大小限制
#proxy_connect_timeout:与后端服务器建立连接的超时时间。注意这个一般不能大于75秒
#proxy_read_timeout:从后端服务器读取响应的超时

gzip调优

gzip on;
gzip_min_length 2k;
gzip_buffers    4 32k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_typestext/plain text/css text/javascriptapplication/json application/javascript application/x-javascriptapplication/xml;
gzip_vary on;
gzip_proxied any;
gzip_disable "MSIE [1-6].";

#gzip on:开启压缩功能  
#gzip_min_length 1k:设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取
#默认值是0,不管页面多大都进行压缩,建议设置成大于1K,如果小与1K可能会越压越大。  
#gzip_buffers 4 32k:压缩缓冲区大小,表示申请4个单位为32K的内存作为压缩结果流缓存,默认值是申请
与原始数据大小相同的内存空间来存储gzip压缩结果。  
#gzip_http_version1.1:压缩版本,用于设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持
GZIP解压,使用默认即可  
#gzip_comp_level 6:压缩比例,用来指定GZIP压缩比,1压缩比最小,处理速度最快,9压缩比最大,传输
速度快,但是处理慢,也比较消耗CPU资源。  
#gzip_types text/css text/xml application/javascript:用来指定压缩的类型,‘text/html’类型总是会被压缩。默认值: gzip_types text/html (默认不对js/css文件进行压缩)  
#gzip_varyon:varyheader支持,改选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用
Squid缓存经过nginx压缩的数据
#gzip_disable:禁用IE6以下的gzip压缩,IE6的某些版本对gzip的压缩支持很不好

缓存设置

#设置缓存空间,存储缓存文件
proxy_cache_path /data/nginx-cache levels=1:2 keys_zone=nginx-cache:20m max_size=50g inactive=168h;

#在location中使用缓存空间,pathname是项目的目录,请自定义
location /pathname { 
    proxy_set_header X-Real-IP $remote_addr;
    proxy_cache nginx-cache;
    proxy_cache_valid 200 304 302 5d;
    proxy_cache_valid any 5d;
    proxy_cache_key '$host:$server_port$request_uri';
    add_header X-Cache '$upstream_cache_status from $host';
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost/pathname;
}

#打开文件的缓存配置
#打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive是指经
过多长时间文件没被请求后删除缓存。
open_file_cache max=65535 inactive=60s;

#文件描述符一直是在缓存中打开的,如果有一个文件在inactive时间内一次没被使用,它将被移除。
open_file_cache_min_uses 1;

#指定多长时间检查一次缓存的有效信息。
open_file_cache_valid 80s;

访问限流调优

#限制用户连接数来预防DOS攻击
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
#限制同一客户端ip最大并发连接数
limit_conn perip 2;
#限制同一server最大并发连接数
limit_conn perserver 20;
#限制下载速度,根据自身服务器带宽配置
limit_rate 300k;

正向代理

server {
      listen 8080;
      resolver 8.8.8.8;
      resolver_timeout 5s;
      proxy_connect;
      proxy_connect_allow 443 563;
      proxy_connect_connect_timeout 10s;
      proxy_connect_read_timeout 10s;
      proxy_connect_send_timeout 10s;
      location / {
          proxy_pass $scheme://$host$request_uri;
          proxy_set_header Host $http_host;
          proxy_buffers 256 4k;
          proxy_max_temp_file_size 0;
          proxy_connect_timeout 30;
      }
      access_log /var/log/proxy/access.log main;
      error_log /var/log/proxy/error.log;
  }

配置终端代理

#在 /etc/profile 文件中增加如下三项。
export proxy="http://{proxy_server_ip}:8080"
export http_proxy=$proxy
export https_proxy=$proxy

#使配置生效
 source /etc/profile

反向代理

location / {
        proxy_pass http://localhost:8088;
        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;
    }

负载均衡

upstream test{ 
  server 0.0.0.0:8082 fail_timeout=5 max_fails=3;
  server 0.0.0.0:8083 fail_timeout=5 max_fails=3;
  ip_hash;}location / {
 proxy_pass http://myproject;
 }

https配置

下载证书

server {
    listen 80;
    server_name xxx.com;   #
    rewrite ^(.*)$ https://$host$1 permanent;   #把http的域名请求转成https


server {
    listen 443;
    server_name xxx.com; # 你的域名
    ssl on;

    #root /var/www/bjubi.com; #前台文件存放文件夹,可改成别的
    #index index.html index.htm;  #上面配置的文件夹里面的index.html
    ssl_certificate  cert/xxx.com.crt;   #改成你的证书的名字
    ssl_certificate_key cert/xxx.com.key;   #证书的名字
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    location / {
        proxy_pass http://127.0.0.1:8080;
                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;
    }
}

完整版配置文件

worker_processes auto;
multi_accept on;
worker_rlimit_nofile 65535;

events {
    worker_connections  65535;
    multi_accept on;
    use epoll;
}

http {
    include     /etc/nginx/mime.types;
    default_type  application/octet-stream;
                      
    log_format main '{"@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",'
    '"xff":"$http_x_forwarded_for",'
    '"referer":"$http_referer",'
    '"agent":"$http_user_agent",'
    '"status":"$status"}';
    
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    
    keepalive_timeout 60;
    keepalive_requests 10240;
    tcp_nodelay on;
    client_header_buffer_size 4k;
    open_file_cache max=102400 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 1;
    client_header_timeout 15;
    client_body_timeout 15;
    reset_timedout_connection on;
    send_timeout 15;
    server_tokens off;
    client_max_body_size 500m;
    proxy_connect_timeout 30s;
    proxy_send_timeout 120s;
    proxy_read_timeout 120s;
    
    limit_conn_zone $binary_remote_addr zone=perip:10m;
    limit_conn_zone $server_name zone=perserver:10m;
    limit_conn perip 2;
    limit_conn perserver 20;
    limit_rate 300k; 

    proxy_cache_path /data/nginx-cache levels=1:2 keys_zone=nginx-cache:20m max_size=50g inactive=168h;

    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 4;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_vary on;
    gzip_disable "MSIE [1-6].";

    include /etc/nginx/conf.d/*.conf;
}


server {
    listen 443;
    server_name www.xxx.com;
    ssl on;
    ssl_certificate cert/证书名称.pem;
    ssl_certificate_key cert/证书名称.key;
    ssl_session_timeout 5m;
    # SSL协议配置
    ssl_protocols SSLv2 SSLv3 TLSv1.2;
    ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
    ssl_prefer_server_ciphers on;
    
    valid_referers none blocked server_names
               *.ygoclub.com;
               
    #日志配置
    access_log  /var/log/nginx/access.log  main gzip=4 flush=5m;
    error_log  /var/log/nginx/error.log  error;
    
    location ~ .*\.(eot|svg|ttf|woff|jpg|jpeg|gif|png|ico|cur|gz|svgz|mp4|ogg|ogv|webm) {
        proxy_cache nginx-cache;
        proxy_cache_valid 200 304 302 5d;
        proxy_cache_key '$host:$server_port$request_uri';
        add_header X-Cache '$upstream_cache_status from $host';
        #所有静态文件直接读取硬盘
        root /usr/share/nginx/html;
        expires 30d; #缓存30天
    }

    location ~ .*\.(js|css)?$
    {
        proxy_cache nginx-cache;
        proxy_cache_valid 200 304 302 5d;
        proxy_cache_key '$host:$server_port$request_uri';
        add_header X-Cache '$upstream_cache_status from $host';
        #所有静态文件直接读取硬盘
        root /usr/share/nginx/html;
        expires      12h;
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    
    location /druid {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_cache nginx-cache;
        proxy_cache_valid 200 10m;
        proxy_pass http://xxxx/druid;
    }
    
    location /api {
       proxy_set_header X-Real-IP $remote_addr;
       proxy_pass http://xxxx/api;
    }
    
    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区