Nginx Proxy Manager (NPM) 是一个基于Nginx的图形化管理工具,可以方便地实现API网关功能,包括认证与授权。以下是详细的实现方案:
# 使用Docker安装
docker run -d \
--name=npm \
-p 80:80 \
-p 443:443 \
-p 81:81 \
-v npm_data:/data \
-v npm_letsencrypt:/etc/letsencrypt \
--restart unless-stopped \
jc21/nginx-proxy-manager:latest
http://<服务器IP>:81
admin@example.com
/ changeme
nginx
location /api {
auth_basic "Restricted API";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend;
}
bash
htpasswd -c /data/nginx/.htpasswd username
nginx-jwt
模块nginx
location /api {
auth_jwt "Restricted API" token=$cookie_auth_token;
auth_jwt_key_file /etc/nginx/jwt_secret.key;
proxy_pass http://backend;
}
oauth2-proxy
:
bash
docker run -d \
--name oauth2-proxy \
-p 4180:4180 \
-v /path/to/config.cfg:/etc/oauth2_proxy.cfg \
bitnami/oauth2-proxy
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
proxy_pass http://backend;
}
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
location /api {
if ($http_apikey != "your-secret-key") {
return 403;
}
proxy_pass http://backend;
}
bash
docker exec -it npm tail -f /data/logs/proxy-host-*_access.log
nginx
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
常见问题及解决方案:
认证失败:
403禁止访问:
速率限制太严格:
limit_req_zone
参数通过以上配置,Nginx Proxy Manager可以成为一个功能强大的API网关,提供灵活的认证与授权机制,同时保持易用性和可管理性。