我想根據請求的路徑授權用戶。例如,只有user1并且user2應該有權訪問/projects/1.
我的/etc/nginx/.htpasswd樣子是這樣的:
user1:$hashed_psswd1
user2:$hashed_psswd2
user3:$hashed_psswd3
...
這是locationnginx 配置中的塊:
location ~ /projects(/.*) {
auth_basic "Please provide credentials";
auth_basic_user_file /etc/nginx/.htpasswd;
include /var/www/html/myapp.com/config/nginx/git-http-backend.conf;
}
和 rails 動作:
def git
redirect_to "#{Rails.configuration.x.domain}/projects/#{@project.id}"
end
身份驗證似乎有效:
$ git clone http://localhost:3000/projects/1
Cloning into '1'...
Username for 'http://localhost:3001': user1
Password for 'http://deploy@localhost:3001':
remote: Enumerating objects: 94, done.
# ... it successfully clones the git repo...
問題是user3能夠克隆專案1,但他不應該能夠克隆這樣的專案。
那么如何根據請求的路徑授權 nginx rails 中的用戶呢?
uj5u.com熱心網友回復:
這是我剛剛使用 OpenResty 1.17.8.2(基于 nginx 1.17.8 核心)測驗的配置,可以確認它是可行的:
map $uri $realm {
~^/projects/ "Protected projects";
~^/images/ "Protected images";
default off;
}
map $uri $authfile {
~^/projects/ /path/to/.htpasswd_projects;
~^/images/ /path/to/.htpasswd_images;
}
server {
...
auth_basic $realm;
auth_basic_user_file $authfile;
...
}
.htpasswd_projects并且.htpasswd_images檔案包含每個自己的用戶/密碼串列。使用上述配置,每個以/projects/前綴開頭的 URI 都受基本授權保護,僅對htpasswd_projects檔案中列出的用戶可用,每個以前綴開頭的 URI/images/都受基本授權保護,僅對檔案中列出的用戶可用htpasswd_images,其余 URI 可用未經所有人授權。
更新
這是另一個示例,.htpasswd根據請求的 URI 使用動態生成的路徑:
location ~ ^/projects/(?<project_id>[^/] ) {
if (!-f /var/www/projects/$project_id/.htpasswd) {
# '.htpasswd' file for the requested project does not exists
# assuming wrong project ID is given, returning HTTP 404 Not found
return 404;
}
auth_basic "Please provide credentials for project $1";
auth_basic_user_file /var/www/projects/$project_id/.htpasswd;
...
}
這將與以下.htpasswd檔案樹一起使用:
/var/www/projects
├── 1
│ └── .htpasswd
├── 2
│ └── .htpasswd
...
您可以將此projects目錄放置在任何您想要的位置,它不依賴于 Web 服務器根目錄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414048.html
標籤:
