3.OpenResty系列之Nginx反向代理

news/2024/7/7 20:15:37
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, 完毕,已验证可正常反向代理


http://lihuaxi.xjx100.cn/news/1846657.html

相关文章

Java Web基础教程

Java Web基础教程 1. Servlet基础 1.1 什么是Servlet Servlet是JavaEE中的标准组件之一,专门用于处理客户端的HTTP请求。并且它必须依赖于Servlet容器(Tomcat就是一个标准的Servlet容器)才能运行。因为Servlet实例的创建和销毁都是由容器负…

线性系统理论 -- 降阶观测器的设计

定理: 若系统能观测,且rankCm,则系统的状态观测器的最小维数是(n-m)。 线性定常时不变系统方程如下(以三阶(n3)单入单出系统为例,有mrankC1): 取变换阵P,有: 对上述系统…

AWS连甩3项Serverless创新,高效创建和操作缓存,用AI优化资源配置性价比

云创科技11月28日拉斯维加斯报道,在一年一度的AWS re:Invent首日,AWS实用计算高级副总裁Peter DeSantis延续Monday Night Live的传统,发表主题演讲并分享了AWS数据库和分析产品组合中的3项Serverless创新,以帮助客户在任何规模下分…

AWL中英文对照表

Sublist 1 sector:部门、 available:可用的、 financial:财务的、 process:过程、 individual:个人的、 specific:具体的、 principle:原则、 estimate:估计、 variables&#xff1…

界面控件DevExpress WinForms Sunburst组件,轻松可视化分层扁平数据!

DevExpress WinForms Sunburst控件允许用户以紧凑和视觉上吸引人的方式可视化分层和扁平数据。 DevExpress WinForms有180组件和UI库,能为Windows Forms平台创建具有影响力的业务解决方案。同时能完美构建流畅、美观且易于使用的应用程序,无论是Office风…

数字人透明屏幕的技术原理是什么?

数字人透明屏幕的技术原理主要包括人脸识别和全息影像技术。其中,人脸识别技术是通过摄像头捕捉游客的面部表情和动作,并将其转化为数据指令,以便与数字人物进行互动。而全息影像技术则是利用透明屏幕,通过全息投影的方式将数字人…

linaro交叉编译工具链下载与使用笔记

笔记 文章目录 笔记确定目标 (aarch64)选择版本(7.5)选择目标(aarch64-linux-gnu)下载地址工具链(gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz)编译测试 &#xff08…

全新仿某度文库网站源码/在线文库源码/文档分享平台网站源码/仿某度文库PHP源码

源码简介: 全新仿某度文库网站源码/在线文库源码,是以phpMySQL开发的,它是仿某度文库PHP源码。有功能免费文库网站 文档分享平台 实现文档上传下载及在线预览。 仿百度文库是一个以phpMySQL进行开发的免费文库网站源码。仿某度文库实现文档…