网上看到多篇先关文章,觉得很不错,这里合并记录一下,仅供学习参考。
模块
nginx-auth-request-module
该模块是nginx一个安装模块,使用配置都比较简单,只要作用是实现权限控制拦截作用。默认高版本nginx(比如1.12)已经默认安装该模块,下面介绍下使用该模块实现多个站点之间的统一权限控制。
例子1
这里用一个例子来说明下,如下例子是包含site1(对应web1)、site2(对应web2)、auth(20.131:7001)在内的三个应用项目,auth项目主要做权限拦截,比如jwt校验等,site1、site2分别为两个受保护的资源站点,只有auth授权通过后才能访问该站点。
实现上述要求nginx配置详情如下(nginx地址为20.198):
upstream web1 {
server 192.168.20.131:3000;
}
upstream web2 {
server 192.168.20.131:3001;
}
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 /api/web1 {
auth_request /auth;
error_page 401 = @error401;
auth_request_set $user $upstream_http_x_forwarded_user;
proxy_set_header X-Forwarded-User $user;
proxy_pass http://web1;
}
location /api/web2 {
auth_request /auth;
error_page 401 = @error401;
auth_request_set $user $upstream_http_x_forwarded_user;
proxy_set_header X-Forwarded-User $user;
proxy_pass http://web2;
}
location /auth {
internal;
proxy_set_header Host $host;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_pass http://192.168.20.131:7001/auth;
}
location @error401 {
add_header Set-Cookie "NSREDIRECT=$scheme://$http_host$reques