我正在使用 nginx 在没有 CGI 后端的嵌入式系统中提供静态文件。我有多个用户名/密码的基本身份验证。我想让一个特定的 URI 根据当前经过身份验证的用户的名称传送不同的内容。
例如,假设浏览器请求 URI/index.html。如果浏览器被认证为用户“developer”,那么它可以得到文件/index_developer.html。相反,如果浏览器被认证为“管理员”,则可以为文件/index_administrator.html 提供服务。
我只希望这种重定向发生在一小部分文件上;大多数将按原样提供。我还需要阻止对实际文件的直接访问,这样就没有人可以绕过系统运行。
最佳答案
首先,有变量 $remote_user
.
我最终得到了以下结构:
$ tree
.
├── _auth
│ ├── admin
│ │ ├── f
│ │ │ └── index.html
│ │ ├── hello.html
│ │ └── index.html
│ └── user
│ ├── f
│ │ └── index.html
│ └── index.html
├── f
│ └── x.html
├── hello.html
├── test.html
└── x
└── index.html
和这个 nginx 配置:
auth_basic "Restricted area";
auth_basic_user_file path/to/passwd/file;
root /path/to/root;
location / {
try_files /_auth/$remote_user$uri
/_auth/$remote_user$uri/index.html
$uri $uri/index.html =404;
}
location /_auth/ {
internal;
}
于是请求/
最终会出现在 /_auth/USER/index.html
, 请求/test.html
将服务/test.html
.并要求/hello.html
将服务/_auth/admin/hello.html
对于用户 admin
和 /hello.html
对于任何其他用户。
直接访问 /_auth/..
被 internal
禁止指令。
关于authentication - 配置 nginx 以将不同的文件返回给具有相同 URI 的不同身份验证用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23506626/