原理
# 編譯 Nginx 時需要添加該模塊 --with-http_auth_request_module
# 該模塊可以將客戶端輸入的用戶名、密碼 username:password 通過 Base64 編碼後寫入 Request Headers 中
# 例如:wang:wang -> Authorization:Basic d2FuZzp3YW5n=
# 然後通過第三方程序解碼後跟數據庫中用戶名、密碼進行比較,Nginx 服務器通過 header 的返回狀態判斷是否認證通過。
本地服務器配置
# 我們先來編輯本機配置文件,也就是用戶直接訪問的域名
shell > vim /usr/local/nginx-1.10.2/conf/vhost/local.conf
server {
listen 80;
server_name local.server.com;
auth_request /auth;
location / {
root html;
index index.html;
}
location /auth {
proxy_pass http://auth.server.com/HttpBasicAuthenticate.php;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
}
驗證服務器配置
shell > vim /usr/local/nginx-1.10.2/conf/vhost/auth.conf # 這是第三方認證服務器,認證邏輯使用的 PHP 代碼
server {
listen 80;
server_name auth.server.com;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/local/nginx-1.10.2/html$fastcgi_script_name;
include fastcgi_params;
}
}
驗證程序
<?php
if(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])){
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
if ($username == 'wang' && $password == '123456'){
return true;
}
}
header('WWW-Authenticate: Basic realm="Git Server"');
header('HTTP/1.0 401 Unauthorized');