Nginx学习----Nginx配置反向代理、负载均衡

本文详细介绍了Nginx配置中的关键部分,包括设置用户和worker进程数以优化连接数,日志管理和格式,以及http核心模块的配置。此外,还讲解了负载均衡的实现,如权重分配和故障转移,并展示了如何通过alias和root处理静态资源。最后,提到了如何在nginx层面封禁IP以及不同层级的IP限制策略。
摘要由CSDN通过智能技术生成


链接: nginx中文文档

一、客户端、代理服务器、服务器之间的关系

绘图工具:diagrams,关联了github地址。
地址:https://github.com/pikefeier/diagrams

在这里插入图片描述
浏览器设置代理,可以隐藏真实ip地址:
在这里插入图片描述

二、解析nginx配置文件

一般有nginx.conf文件和conf.d/xxx.conf文件,在nginx.conf中通过include方式引入

 # Load config files from the /etc/nginx/conf.d/ directory
 include /etc/nginx/conf.d/*.conf;
nginx.conf

【点击下载】

①. 查找nginx.conf所在的位置:

假设不知道具体路径,执行 whereis nginx,或者执行查找命令:

cd / # 定位到根目录
find -name 'nginx.conf'
>./etc/nginx/nginx.conf
####或者whereis nginx
②.nginx配置文件
  1. 主标签段:连接数+进程数

    #### 连接数+进程数 ####
    	# 指定用哪个用户运行Nginx,为避免安全问题,最小权限原则,
    	# nginxuser 对静态资源有只读权限就行。如 user www www 
    user username[groupname] 
    	# Nginx worker进程个数:其数量直接影响性能。每个worker进程都是单线程的进程
    	# 一般一个进程足够了,你可以把连接数设得很大。(worker_processes: 1,
    	#worker_connections: 10,000)如果有SSL、gzip这些比较消耗CPU的工作,而且是
    	#多核CPU的话,可以设为和CPU的数量一样。(worker_processes: CPU核心数)或者要
    	#处理很多很多的小文件,而且文件总大小比内存大很多的时候,也可以把进程数增加,
    	#以充分利用IO带宽(主要似乎是IO操作有block)
    worker_processes 8;
    	#最大打开文件数限制,注意:linux系统也有文件打开最大限制:cd /etc/security/limit.conf中。
    worker_rlimit_nofile 65536;
    

    推荐文档:
    1 记一次worker_rlimit_nofile配置引发的问题
    2 /etc/security/limits.conf 详解与配置
    3修改 Nginx 进程最大可打开文件数

  2. 主标签段:日志相关

    #### 用于调试、定位问题的配置项 ####
    	# 日志位置 path/file
    error_log   /var/log/nginx/error.log;
    	# 日志级别:不写默认error
    	# debug、info、notice、warn、error、crit、alert、emerg从左至右级别依次增大
    error_log  logs/error.log  info;
    	#通过 PID 文件可以判断是否已经有一个实例正在运行。防止意外启动多个进程实例
    pid   /var/run/nginx.pid;
    

    当日志位置:path/file 的值为 /dev/null时,这样就不会输出任何日志了,这也是关闭error日志的唯一手段

  3. 优化项,一般指event块里

    #### events优化项 ####
    events {
    	# 最大连接数:worker-connection*worker_processes /4
       worker_connections 65536;
       # io采用多路复用
       use epoll;
       #仅对指定的客户端输出debug级别的日志: 语法:debug_connection[IP|CIDR]
       #debug_connection 10.224.66.14; 
    }
    

    并发数(假设10万):=worker_connections * worker_processes /4
    –>worker_connections =50000,但是这里/4有争议。
    io多路复用:epoll模型,不用从用户态拷贝到内核态,减少了select和poll模型的轮询。

    推荐文档:
    1 Nginx核心要领五
    2 /etc/security/limits.conf 详解与配置

  4. http 核心模块

    #### http 核心模块 ####
    http{
    	# 如果不指定mime type,则默认会以text/plain的形式处理,也就是说,
    	# 浏览器会以纯文本的形式来处理css和js文件,所以无法正常加载样式。
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
       #列出不同的日志格式
       log_format  main  '$remote_addr - $upstream_cache_status $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$request_time" $upstream_addr';
    
       log_format timing  '$remote_addr - $remote_user [$time_local]  $request '
                       'upstream_http_content_type: $upstream_http_content_type'
                       'upstream_response_time: $upstream_response_time '
                       'request_time: $request_time';
       #用于记录客户端(用户)IP地址,浏览器的一些信息,访问时间等
       #即谁来登陆了,从哪里登陆的,登陆后发生了什么
       access_log  /var/log/nginx/access.log  main;
       error_log   /var/log/nginx/error.log;
       #keepalive_timeout参数是一个请求完成之后还要保持连接多久,不是请求时间多久,目的是保持长连接,
       #减少创建连接过程给系统带来的性能损耗,类似于线程池,数据库连接池。
       keepalive_timeout  65;
       #嵌入其他conf:   Load config files from the /etc/nginx/conf.d/ directory
       include /etc/nginx/conf.d/*.conf;
       #其他
       sendfile           on;
        tcp_nopush         on;
        tcp_nodelay        on;
        server_tokens      off;
       gzip               On;
       gzip_types         text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript image/x-icon;
        gzip_disable       "MSIE [1-6].(?!.*SV1)";
        gzip_static        on;
        gzip_vary          on;
        gzip_comp_level    2;
        gzip_min_length    1024;
        gzip_buffers       16 8k;
        client_max_body_size 4m;
    }
    

    推荐文档:
    1 Web部署到Nginx后静态文件加载不正常(MIME TYPE问题)


上述是nginx.conf的基本配置,具体到项目中,可以自定义配置.conf文件,一般放在conf.d/下

  1. 负载均衡配置

    # 负载均衡配置 :我们经常用的是配置权重的方式
    upstream projectName{
    # 客户端接收请求,并保存带route的cookie。当客户端下一次发送请求时,会带上route,
    # nginx根据接收到的cookie中的route值,转发给对应的后端服务器。sticky模块不能与ip_hash同时使用
     sticky;
     # weight 配置权重
     # 默认:fail_timeout为10s,max_fails为1次。
     server 127.0.0.1:8082 weight=9 max_fails=3 fail_timeout=5s;
     server 127.0.0.1:8081 weight=1 max_fails=3 fail_timeout=5s;
    }
    

    Nginx基于连接探测,如果发现后端异常,在单位周期为fail_timeout设置的时间,中达到max_fails次数,这个周期次数内,如果后端同一个节点不可用,那么接将把节点标记为不可用,并等待下一个周期(同样时常为fail_timeout)再一次去请求,判断是否连接是否成功。如果成功,将恢复之前的轮询方式,如果不可用将在下一个周期(fail_timeout)再试一次。

    推荐文档:
    1 nginx会话保持之sticky模块
    2 Nginx负载均衡配置fail_timeout

  2. server配置

    #### server配置 ####
    server{
    # 一般nginx监听80端口
    listen 80;
    # server_name 同样也可以使用 ip进行匹配 
    # 也可以使用正则匹配:~^(?.+)\.domain\.com$
    #主机名称:其后可以跟多个主机名称,开始处理一个HTTP请求时,nginx会取出header头中的Host,
    #与每个server中的server_name进行匹配,以此决定到底由那一个server来处理这个请求。
    #有可能一个Host与多个server块中的server_name都匹配,这时会根据匹配优先级来选择实际处理的server块。
    #优先级为精确匹配>正则匹配
    server_name     www.test.com  www.test2.com;
    access_log   /var/log/nginx/project1-access.log main;
    error_log    /var/log/nginx/project1-error.log;
    rewrite_log off;
    error_page
    
    #root方式:加前缀 root+path
    # 意思是有一个请求的URL是 /download/index/test.html, 那么Web服务器就会返回服务器上 /opt/wab/html/download/index/test.html 文件的内容
    location /download/ {
           root    /opt/wab/html/;	
    }         
    
      #alias方式:别名替换 alias替换path
    # 意思是有一个请求的URL是 /download/index/test.html, 那么Web服务器就会返回服务器上 /opt/wab/html/index/test.html 文件的内容
    location /download/ {
           alias   /opt/wab/html/;	
    }     
    # 匹配所有:root匹配index首页  。顺序是从左到右,即index2.html优先级高于index.html
     location / {
            root   html;
            index  index2.html index.html;
       }
        
    # 按照正则匹配  ~ ^/images/  匹配image开头的   ~* \.(gif|jpg|jpeg)$ 匹配gif/jpg/jpeg结尾
    location = ~ ^/images/ {
     expires 30d;
    }  		
    # 匹配请求
    	location ~ ^/project {
        proxy_pass        http://127.0.0.1:8080;
        client_max_body_size 1000m;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  Host $http_host;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header   X-NginX-Proxy    true;
        proxy_redirect      off;
        proxy_read_timeout 86400;
        proxy_buffering off;
        #建议使用nginx的应用,都加上proxy_ignore_client_abort on,默认 proxy_ignore_client_abort 是关闭的,
        #此时在请求过程中如果客户端端主动关闭请求或者客户端网络断掉,那么 Nginx 会记录 499
        #开启后Nginx 会等待后端处理完(或者超时),然后 记录 「后端的返回信息」 到日志。所以,如果后端 
        #返回 200, 就记录 200 ;如果后端放回 5XX ,那么就记录 5XX 
        proxy_ignore_client_abort on;
      }
    
    
  3. 静态资源配置

    # 静态资源配置
    location ^~ /image/ {
    alias	/nas/project/image/;
    }
    
  4. 禁止访问

    # Block access to hidden files 阻止访问隐藏文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
      }
    
如果想封掉ip,可以怎么做?
  1. 在linux服务器层进行ip限制

  2. 在nginx反向代理层进行ip限制
    在nginx 层面的封禁, req还是会打进来, 让nginx 返回 403, 占用资源

    http{
        # ....
        include blacklist.conf;
    }
    

    blacklist.conf:

    deny 182.84.132.13;
    deny 117.82.174.128;
    deny 182.150.146.215;
    deny 182.148.58.231;
    
  3. 在项目server层进行ip过滤
    根据具体业务需求,在项目的数据库中(redis或者mysql)建立ip表,当在请求服务器时进行ip判断。

    参考文章:
    1.linux , nginx: 封禁IP的办法【转】
    2.Nginx如何封禁IP和IP段的实现

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值