nginx七层代理转发和四层代理转发实战

nginx源码编译安装,本安装版本为V1.15.2

./configure --with-stream --add-module=./nginx-module-vts --with-http_gzip_static_module --with-http_stub_status_module --with-http_ssl_module

--with-stream为四层代理转发:基于TCP,UDP;

默认支持七层代理转发:基于HTTP;

使用场景:在阿里云申请了一台20M带宽的高性能的云主机,做为唯一入口(本环境没有考虑HA)。

实现目的:

1)缓存服务;

2)后端无状态的负载均衡;

3)mysql等中间件的反向代理。

具体NGINX配置文件如下,可修改少数的数据,直接 使用。

user  nginx nginx;
worker_processes auto;
error_log  /usr/local/nginx/logs/nginx_error.log  crit;
pid        /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;

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

http
    {
        vhost_traffic_status_zone;
        include       mime.types;
        #include proxy.conf;
        #include luawaf.conf;
        default_type  application/octet-stream;

        server_names_hash_bucket_size 128;
        client_header_buffer_size 32k;
        large_client_header_buffers 4 32k;
        client_max_body_size 50m;

        sendfile   on;
        tcp_nopush on;
        underscores_in_headers on;
        keepalive_timeout 60;

        tcp_nodelay on;
        aio_write           on;
        log_subrequest      on;

        reset_timedout_connection on;
        keepalive_requests 100;


        types_hash_max_size             2048;
        map_hash_bucket_size            64;

        proxy_headers_hash_max_size     512;
        proxy_headers_hash_bucket_size  64;

        variables_hash_bucket_size      128;
        variables_hash_max_size         2048;

        ignore_invalid_headers          on;

        limit_req_status                503;


        gzip on;
        gzip_comp_level 5;
        gzip_http_version 1.1;
        gzip_min_length 256;
  gzip_types application/atom+xml application/javascript application/x-javascript application/json application/rss+xml application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/svg+xml image/x-icon text/css text/plain text/x-component;
        gzip_proxied any;
        gzip_vary on;

#       fastcgi_connect_timeout 300;
#        fastcgi_send_timeout 300;
#        fastcgi_read_timeout 300;
#        fastcgi_buffer_size 64k;
#        fastcgi_buffers 4 64k;
#        fastcgi_busy_buffers_size 128k;
#        fastcgi_temp_file_write_size 256k;
#        fastcgi_intercept_errors on;

        # Custom headers for response

        server_tokens on;

        # disable warnings
        uninitialized_variable_warn off;
        access_log off;
        server_name_in_redirect off;
        port_in_redirect off;
        proxy_cache_path /data/nginx/imgcache/ levels=1:2 keys_zone=imgcache:100m inactive=1d max_size=10g;
        proxy_temp_path /data/nginx/imgtemp;


        upstream webservers {
            least_conn;
            keepalive 32;
            server 192.168.0.152:10080 max_fails=0 fail_timeout=0 weight=5 down;
            server 192.168.0.148:10080 max_fails=0 fail_timeout=0 weight=5 down;
        }
        upstream gateways {
            least_conn;
            keepalive 32;
            server 192.168.0.153:10080 max_fails=0 fail_timeout=0 weight=5;
            server 192.168.0.152:10080 max_fails=0 fail_timeout=0 weight=5 down;
        }
        upstream kibana {
            keepalive 32;
            server 192.168.0.148:5601;
        }
        upstream mysql-monitor {
           keepalive 32;
           server 192.168.0.145:7001;
        }

        # Obtain best http host
        map $http_host $this_host {
                default          $http_host;
                ''               $host;
        }

        map $http_x_forwarded_host $best_http_host {
                default          $http_x_forwarded_host;
                ''               $this_host;
        }

        # Retain the default nginx handling of requests without a "Connection" header
        map $http_upgrade $connection_upgrade {
                default          upgrade;
                ''               close;
        }

        map $http_x_forwarded_for $the_real_ip {

                default          $remote_addr;

        }
        # Reverse proxies can detect if a client provides a X-Request-ID header, and pass it on to the backend server.
        # If no such header is provided, it can provide a random value.
        map $http_x_request_id $req_id {
                default   $http_x_request_id;

                ""        $request_id;

        }
        map $pass_server_port $pass_port {
                443              443;
                default          $pass_server_port;
        }
        map $http_x_forwarded_port $pass_server_port {
                default           $http_x_forwarded_port;
                ''                $server_port;
        }
        # trust http_x_forwarded_proto headers correctly indicate ssl offloading
        map $http_x_forwarded_proto $pass_access_scheme {
                default          $http_x_forwarded_proto;
                ''               $scheme;
        }

        # validate $pass_access_scheme and $scheme are http to force a redirect
        map "$scheme:$pass_access_scheme" $redirect_to_https {
                default          0;
                "http:http"      1;
                "https:http"     1;
        }
#gateways server------------------------
        server {
            listen 80;
            listen [::]:80;
            listen 443  ssl;
            listen [::]:443  ssl;
            index index.html index.htm index.php;
            root /usr/local/nginx/html;
            server_name  localhost;
            server_tokens off;
            ssl_certificate      server.crt;
            ssl_certificate_key  server.key;

 ssl_protocols TLSv1 TLSv1.1 TLSv1.2;ssl_ciphers ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!AESGCM;
            ssl_prefer_server_ciphers on;
            ssl_session_cache shared:SSL:10m;
            ssl_session_timeout 10m;
            #error_page   404   /404.html;
            #include enable-php.conf;
        

            location / {
                        proxy_set_header Host                   $best_http_host;
                        proxy_set_header                        Upgrade           $http_upgrade;
                        proxy_set_header                        Connection        $connection_upgrade;
                        proxy_set_header X-Request-ID           $req_id;
                        proxy_set_header X-Real-IP              $the_real_ip;
                        proxy_set_header X-Forwarded-For        $the_real_ip;
                        proxy_set_header X-Forwarded-Host       $best_http_host;
                        proxy_set_header X-Forwarded-Port       $pass_port;
                        proxy_set_header X-Forwarded-Proto      $pass_access_scheme;
                        proxy_set_header X-Original-URI         $request_uri;
                        proxy_set_header X-Scheme               $pass_access_scheme;
                        proxy_set_header X-Original-Forwarded-For $http_x_forwarded_for;
                        proxy_set_header Proxy                  "";
                        proxy_connect_timeout                   5s;
                        proxy_send_timeout                      60s;
                        proxy_read_timeout                      60s;

                        proxy_buffering                         "off";
                        proxy_buffer_size                       "4k";
                        proxy_buffers                           4 "4k";
                        proxy_request_buffering                 "on";

                        proxy_http_version                      1.1;
                        proxy_set_header Connection             "";
                        proxy_cookie_domain                     off;
                        proxy_cookie_path                       off;

                        proxy_next_upstream                     error timeout;
                        proxy_next_upstream_tries               3;

                        proxy_pass   http://gateways;
                        proxy_redirect                          off;
                        #limit_req zone=mylimit burst=5;
            }

            location ~ .*\.(js|css)?$
            {
                expires      12h;
            }

            location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
                log_not_found off;
                access_log off;
                expires 7d;
                proxy_cache imgcache;
                proxy_cache_valid 200 302 1d;
                proxy_cache_valid 404 10m;
                proxy_cache_valid any 1h;
                proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
                proxy_pass  http://192.168.0.152:8080;
            }
            location /ng_status {
                vhost_traffic_status_display;
                vhost_traffic_status_display_format html;
                allow 127.0.0.1;
                allow 192.168.0.0/24;
                allow 10.31.186.119/32;
                #stub_status on;
                deny all;
                access_log off;
            }

            location ~ /\. {
                deny all;
            }
                access_log off;
                #access_log  /usr/local/nginx/logs/access.log;
           }


        #kibana server
        server {
                listen 5601;
                location / {
                auth_basic "User Authentication";
                auth_basic_user_file /usr/local/nginx/passwd.db;
                proxy_pass   http://kibana;
                access_log off;
                }


                }

        #mysql-monitor
        server {
                listen 7001;
                location / {
                auth_basic "User Authentication";
                auth_basic_user_file /usr/local/nginx/passwd.db;
                proxy_pass   http://mysql-monitor;
                access_log off;
                }


                }
        #img-cache
        server {

                listen 8080;
                server_name localhost;
                include /www/server/nginx/conf/enable-php-72.conf;
                root /usr/local/nginx/html/imgcache;
                location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
                        expires      30d;
                        access_log  /usr/local/nginx/logs/pic.log;
                }
                access_log off;
                }

}

stream {
        upstream mysql-server {
                hash $remote_addr consistent;
                server 192.168.0.145:3306;
                server 192.168.0.146:3306;
        }

        server {
                listen 33306;
                proxy_connect_timeout 1s;
                proxy_timeout 3s;
                proxy_pass mysql-server;
}

    log_format log_stream [$time_local]$protocol-$status-$bytes_sent-$bytes_received-$session_time;
    access_log /usr/local/nginx/logs/mysql_access.log log_stream;
    error_log  /usr/local/nginx/logs/mysql_error.log;

    # TCP services

    # UDP services
}

NGINX(Engine X)是一款流行的开源Web服务器软件和反向代理服务器。它支持两种主要的转发方式:四层转发七层转发四层转发(Layer 4 Forwarding,L4): 四层转发基于TCP/IP协议栈进行数据包转发。在这种方式下,NGINX根据数据包中的IP地址和端口号进行匹配,并根据匹配结果将请求发送到相应的服务器。这种转发方式基于网络层的IP地址和传输层的端口号,与HTTP协议无关。 优点: * 速度快:直接基于网络层进行数据包转发,无需解析HTTP请求中的内容。 * 适合大规模流量:在高并发情况下,能够处理大量的数据包,具有良好的性能。 缺点: * 不适用于基于HTTP应用的流量:由于只关注网络层信息,无法处理HTTP协议中的内容,例如应用层的信息(如用户身份验证、权限管理等)。 * 不适用于复杂的HTTP请求:对于复杂的HTTP请求,可能需要使用七层转发进行处理。 七层转发(Layer 7 Forwarding,L7): 七层转发是基于HTTP协议层进行数据包转发的。在这种方式下,NGINX解析HTTP请求和响应中的内容,并根据请求中的URL、HTTP方法、HTTP头部等信息进行匹配,将请求发送到相应的服务器。这种转发方式基于HTTP协议的内容,可以处理基于HTTP的应用流量。 优点: * 支持复杂的HTTP应用:能够处理基于HTTP的应用流量,如Web应用服务器(如Tomcat、Nginx等)。 * 可扩展性强:可以根据需要配置各种过滤器、插件等,以支持不同的应用场景。 * 可配置性高:可以根据实际需求调整七层转发的规则,以满足不同的业务需求。 缺点: * 性能影响:解析HTTP内容需要消耗一定的CPU和内存资源,可能会对性能产生一定的影响。 * 需要配置规则:对于复杂的HTTP请求,需要配置相应的规则才能正确转发。 总的来说,四层转发适用于大规模的、基于网络层信息的流量转发,而七层转发则更适合处理复杂的、基于HTTP协议的应用流量。在实际应用中,可以根据具体需求选择合适的转发方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值