3.OpenResty系列之Nginx反向代理

1. Nginx简介

Nginx (engine x) 是一款轻量级的 Web 服务器 、反向代理服务器及电子邮件(IMAP/POP3)代理服务器

什么是反向代理?

反向代理(Reverse Proxy)方式是指以代理服务器来接受 internet 上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给 internet 上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器

2. Nginx基本命令
nginx -s stop       # 快速关闭Nginx,可能不保存相关信息,并迅速终止web服务。
nginx -s quit       # 平稳关闭Nginx,保存相关信息,有安排的结束web服务。
nginx -s reload     # 因改变了Nginx相关配置,需要重新加载配置而重载。
nginx -s reopen     # 重新打开日志文件。
nginx -c filename   # 为 Nginx 指定一个配置文件,来代替缺省的。
nginx -t            # 不运行,仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。
nginx -v            # 显示 nginx 的版本。
nginx -V            # 显示 nginx 的版本,编译器版本和配置参数。

如果不想每次都敲命令,可以在安装目录下新添一个启动批处理文件D:\openresty-1.21.4.2-win64\startup.bat,双击即可运行。内容如下

@echo off
rem 如果启动前已经启动nginx并记录下pid文件,会kill指定进程
nginx.exe -s stop

rem 测试配置文件语法正确性
nginx.exe -t -c conf/nginx.conf

rem 显示版本信息
nginx.exe -v

rem 按照指定配置去启动nginx
nginx.exe -c conf/nginx.conf
3. Nginx反向代理实践

nginx.conf 配置文件如下:


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


# 工作模式及连接数上限
events {
    
    
    worker_connections  1024; # 单个后台worker process进程的最大并发连接数
}


http {
    
    
    # 设定mime类型(邮件支持类型),类型由mime.types文件定义
    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 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为 on, 如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
    sendfile        on;
    #tcp_nopush     on;

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

    #gzip  on;

    upstream front_server{
    
    
      # Vue前端本地启动地址,需在vue.config.js的devServer中配置allowedHosts: "all",否则会报Invalid Host header
      server 127.0.0.1:8081;
    }
    upstream api_server{
    
    
      # 微服务后端启动端口
      server 127.0.0.1:8080;
    }

    server {
    
    
        listen       80;
        server_name  localhost;

        # 编码格式
	    charset utf-8;

        #access_log  logs/host.access.log  main;

        # 反向代理的路径(和upstream绑定),location 后面设置映射的路径
        location ~ ^/ {
    
    
            proxy_pass http://front_server;
        }
        # 跨域配置
        location ~ ^/api/ {
    
    
            #include enable-cors.conf;
            proxy_pass http://api_server;
            rewrite "^/api/(.*)$" /$1 break;
        }

        location /hello {
    
    
            default_type 'text/plain';
            content_by_lua_block {
    
    
                ngx.say("Hello, OpenResty!")
            }
        }

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


    # 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 {
    
    
    # 监听443端口。443为知名端口号,主要用于HTTPS协议   
    #    listen       443 ssl;
    #    server_name  localhost;
    # ssl证书文件位置(常见证书文件格式为:crt/pem)
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
    # ssl配置参数(选择性配置)
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
    # 数字签名,此处使用MD5
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

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

}

其中enable-cors.conf配置如下

# allow origin list
set $ACAO '*';

# set single origin
# 替换为自己域名
if ($http_origin ~* (localhost)$) {
    
    
  set $ACAO $http_origin;
}

if ($cors = "trueget") {
    
    
    add_header 'Access-Control-Allow-Origin' "$http_origin";
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}

if ($request_method = 'OPTIONS') {
    
    
  set $cors "${cors}options";
}

if ($request_method = 'GET') {
    
    
  set $cors "${cors}get";
}

if ($request_method = 'POST') {
    
    
  set $cors "${cors}post";
}

OK, 完毕,已验证可正常反向代理

猜你喜欢

转载自blog.csdn.net/SJshenjian/article/details/134628617