nginx 使用小记

前言:

nginx 在均衡负载和反向代理上作用巨大,是每个程序员的必备技能。

1. nginx 简介

Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用 nginx 网站用户有:几乎所有知名厂商。

2. 正向代理和反向代理

都说 nginx 可以做反向代理,那问题来了,啥是反向代理?正向代理又是啥意思?
举例说明:
A(爬虫机器),B(爬虫代理服务器),C(负载均衡服务器),D(后端服务器集群)

  1. 正向代理:
    因为是网络爬虫,对外暴漏 A 的 ip 有风险,所以 A 挂着 B 代理,让 B 去请求 C,C 返回结果到 B,B 再把结果给 A;整个数据流中,C 完全不知道 A 的存在,B 行使正向代理的角色。
  2. 反向代理
    从 B 来的请求到 C,C 并不是真正提供服务的机器,它会把请求分发给 D 服务器集群中的一台服务器,D 处理好了后会把结果返回给 C,C 再把结果给 B,B 完全不知道 D 的存在,C 行使反向代理的角色。
3. 安装 nginx

建议去官网查阅文档:http://nginx.org/en/linux_packages.html
当然,一般机器的源也会有 nginx 的相关信息,可以直接运行命令安装

yum install nginx

tips:

  1. 如果用官网的方式,默认下载最新稳定版
  2. yum clean all && yum makecache 更新缓存(如果有源的变动)
  3. 如果yum不行就用源码安装
    yum install -y gcc-c++
    yum install -y pcre pcre-devel
    yum install -y zlib zlib-devel
    yum install -y openssl openssl-devel
    wget -c http://nginx.org/download/nginx-1.18.0.tar.gz
    tar -zxvf nginx-1.18.0.tar.gz
    cd nginx-1.18.0
    ./configure --prefix=[指定目录安装]
    make
    make install
    
  4. 或者使用rpm包安装
     rpm -ivh http://nginx.org/packages/centos/7/x86_64/RPMS/nginx-1.18.0-1.el7.ngx.x86_64.rpm
    
4. 配置说明

tips: 理解即可,一般不需要改默认配置,步骤 5 会应用举例

配置文件: /etc/nginx/nginx.conf

#user  nginx;

#开启进程数 <=CPU数 
worker_processes  1;

#错误日志保存位置
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#进程号保存文件
#pid        logs/nginx.pid;

#每个进程最大连接数(最大连接=连接数x进程数)每个worker允许同时产生多少个链接,默认1024
events {
    worker_connections  1024;
}


http {
    #文件扩展名与文件类型映射表
    include       mime.types;
    #默认文件类型
    default_type  application/octet-stream;

    #日志文件输出格式 这个位置相于全局设置
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    #请求日志保存位置
    #access_log  logs/access.log  main;
    
    #打开发送文件
    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    #连接超时时间
    keepalive_timeout  65;

    #打开gzip压缩
    #gzip  on;
    
    #设定请求缓冲
    #client_header_buffer_size 1k;
    #large_client_header_buffers 4 4k;
    
    #设定负载均衡的服务器列表
    #upstream myproject {
        #weigth参数表示权值,权值越高被分配到的几率越大
        #max_fails 当有#max_fails个请求失败,就表示后端的服务器不可用,默认为1,将其设置为0可以关闭检查
        #fail_timeout 在以后的#fail_timeout时间内nginx不会再把请求发往已检查出标记为不可用的服务器
    #}
    
    #webapp
    #upstream myapp {   
    # server 192.168.122.133:8080 weight=1 max_fails=2 fail_timeout=30s;   
    # server 192.168.122.134:8080 weight=1 max_fails=2 fail_timeout=30s;   
    #} 

    #配置虚拟主机,基于域名、ip和端口
    server {
        #监听端口
        listen       80;
        #监听域名
        server_name  localhost;

        #charset koi8-r;
        
        #nginx访问日志放在logs/host.access.log下,并且使用main格式(还可以自定义格式)
        #access_log  logs/host.access.log  main;

        #返回的相应文件地址
        location / {
            #设置客户端真实ip地址
            #proxy_set_header X-real-ip $remote_addr;       
            #负载均衡反向代理
            #proxy_pass http://myapp;
            
            #返回根路径地址(相对路径:相对于/usr/local/nginx/)
            root   html;
            #默认访问文件
            index  index.html index.htm;
        }

        #配置反向代理tomcat服务器:拦截.jsp结尾的请求转向到tomcat
        #location ~ \.jsp$ {
        #    proxy_pass http://192.168.122.133:8080;
        #}      
        
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        #
        
        #错误页面及其返回地址
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
    
    #虚拟主机配置:
    server {
        listen 1234;
        server_name wolfcode.cn;
        location / {
        #正则表达式匹配uri方式:在/usr/local/nginx/wolfcode.cn下 建立一个test123.html 然后使用正则匹配
        #location ~ test {
            ## 重写语法:if return (条件 = ~ ~*)
            #if ($remote_addr = 192.168.122.1) {
            #       return 401;
            #}      
            
            #if ($http_user_agent ~* firefox) {
            #      rewrite ^.*$ /firefox.html;
            #      break;
            #}          
                        
            root wolfcode.cn;
            index index.html;
        }
        
        #location /goods {
        #       rewrite "goods-(\d{1,5})\.html" /goods-ctrl.html;
        #       root wolfcode.cn;
        #       index index.html;
        #}
        
        #配置访问日志
        access_log logs/wolfcode.cn.access.log main;
    }
    


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
5. 举例实战

机器(局域网,外部无法访问):
A:10.139.5.69
B:10.154.2.152

需求描述:在 A 和 B 上部署后端服务,并在 A 上部署 nginx 做负载均衡

  1. 准备后端程序
    请求路由:ip:9000/test/check/query?keyword=
    返回: keyword 的值
  2. 在 A 上安装 nginx (目前官方稳定版 1.18.0)
    1)配置 /etc/nginx/nginx.conf,只加了 upstream app{} 其它都默认
user  nginx;
worker_processes  1;

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


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

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

    upstream app{
	server 10.154.2.152:9000 weight=100;
	server 10.139.5.69:9000 weight=100;
    }

}

2)配置 /etc/nginx/conf.d/default.conf,只加了 location /test{} 其它都默认

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /test {
	add_header backendIP $upstream_addr;
	add_header backendCode $upstream_status;
        proxy_pass http://app;
    }

    #error_page  404              /404.html;

    # 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;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
  1. 页面调试看效果
    启动 nginx,可能涉及到的命令如下
service nginx start		启动nginx服务
service nginx restart		重启nginx服务
service nginx stop		停止nginx服务
nginx -t		校验nginx配置文件是否正确

或者进入到nginx命令目录下执行:
./nginx -c [指定conf启动]
./nginx -s [stop,quit,reload]

location /test{} 加了两个 head 返回参数,用于记录请求具体分发到哪台机器
两次页面访问 http://10.139.5.69/test/check/query?keyword=999
在这里插入图片描述
在这里插入图片描述
其中红框里记录的就是具体为本次请求提供服务的服务器,两次请求后台服务器不同,确定 nginx 的转发和负载均衡生效。

6. 配置项 location 转发说明
   location /api1/ {
           proxy_pass http://localhost:8080;
        }
   # http://localhost/api1/xxx -> http://localhost:8080/api1/xxx
 
 
   location /api2/ {
           proxy_pass http://localhost:8080/;
        }
   # http://localhost/api2/xxx -> http://localhost:8080/xxx
 
 
   location /api3 {
           proxy_pass http://localhost:8080;
        }
   # http://localhost/api3/xxx -> http://localhost:8080/api3/xxx
 
 
   location /api4 {
           proxy_pass http://localhost:8080/;
        }
   # http://localhost/api4/xxx -> http://localhost:8080//xxx,请注意这里的双斜线,好好分析一下。
 
 
   location /api5/ {
           proxy_pass http://localhost:8080/haha;
        }
   # http://localhost/api5/xxx -> http://localhost:8080/hahaxxx,请注意这里的haha和xxx之间没有斜杠,分析一下原因。
 
   location /api6/ {
           proxy_pass http://localhost:8080/haha/;
        }
   # http://localhost/api6/xxx -> http://localhost:8080/haha/xxx
 
   location /api7 {
           proxy_pass http://localhost:8080/haha;
        }
   # http://localhost/api7/xxx -> http://localhost:8080/haha/xxx
 
   location /api8 {
           proxy_pass http://localhost:8080/haha/;
        }
  # http://localhost/api8/xxx -> http://localhost:8080/haha//xxx,请注意这里的双斜杠。
7. 参考文档
  1. Nginx基本功能及其原理
  2. Nginx搭建负载均衡集群
  3. 正向代理与反向代理区别与nginx实现负载均衡
  4. NGINX配置文件详解
  5. nginx资源转发路径斜杠问题
  6. 官网
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值