自定义nginx启动

右键/以管理员身份运行

image.png

切换到nginx路径/运行nginx
cd /hhh-nginx-bin-1.24.0
./nginx

image.png

查看是否运动成功

image.png

hello world

nginx 安装njs 模块

yum install nginx-module-njs

引用 njs 模块

// nginx.conf
 load_module modules/ngx_http_js_module.so;

 events {}
 http {
 server {}
}

运行

// nginx.conf

 load_module modules/ngx_http_js_module.so;

 events {}

 http {
   js_path "/etc/nginx/njs/";

   js_import index.js;

   server {
     listen 80;

     location / {
       js_content index.hello;
     }
  }
}
// /etc/nginx/njs

function hello(r) {
  r.return(200, "Hello world,  index!");
}

export default { hello };

image.png

image.png

授权认证

后端项目

  1. 监听端口为8080

nginx.conf

http {
    #引入njs项目
    js_path "./../njs/";
    #引入njs中导出的js模块
    js_import main from http/authorization/auth_request.js;

    server {
    #nginx起一个端口
    listen 8001;
    # 过滤所有8001下所有的请求,如需监听特定的路径,如请求/secure/{xxx},则形式为`location /secure/`
    location / { 
        # 发送一个子请求
        auth_request /validate; 
        # 代理8080端口(后端项目)
        proxy_pass http://127.0.0.1:8080;
    }
    # 处理子请求
    location /validate {
        # 只允许国内访问
        internal;
        # 自定义返回内容
        js_content main.authorize;
    }
}
}

njs

http/authorization/auth_request.js
function authorize(r) {
  var Authorization = r.headersIn.Authorization;

  if (!Authorization) {
    r.error("没有对应的请求头,请配置");
    r.return(401);
    return;
  }
  r.return(200);
}

export default { authorize };

结果

没有对应的请求头

image.png

有对应的请求头

image.png


aaaa
5 声望0 粉丝

« 上一篇
电子表格
下一篇 »
nginx