Nginx 提供了多种认证方式,以下是常见的几种实现方法:
这是最简单的 HTTP 认证方式:
sudo htpasswd -c /etc/nginx/.htpasswd username
server {
...
location /protected/ {
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
location /admin/ {
allow 192.168.1.0/24;
allow 10.1.1.0/16;
deny all;
}
server {
ssl_client_certificate /path/to/ca.crt;
ssl_verify_client on;
location /secure/ {
if ($ssl_client_verify != SUCCESS) {
return 403;
}
}
}
需要配合 Lua 或 OpenResty:
location /api/ {
access_by_lua_block {
local jwt = require("resty.jwt")
local auth_header = ngx.var.http_Authorization
if not auth_header then
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
local jwt_obj = jwt:verify("your-secret-key", auth_header)
if not jwt_obj.verified then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
}
可以使用第三方工具如 oauth2-proxy 配合 Nginx 实现。
需要安装 nginx-auth-ldap
模块:
auth_ldap "Forbidden";
auth_ldap_servers ldap1;
location /secure/ {
auth_ldap "LDAP Authentication";
auth_ldap_servers ldap1;
}
需要哪种认证方式的详细配置,我可以提供更具体的指导。