指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

nginx简单访问控制的两种实现方式:
1、auth_basic 本机认证
2、ngx_http_auth_request_module 第三方认证

第一种实现方式:

server {
    listen       80;
    server_name  local.server.com;
    
    auth_basic "User Authentication";
    auth_basic_user_file /usr/local/nginx-1.10.2/conf/pass.db; //需要维护 pass.db 文件
    
    location / {
        root   /data/www;
        index  index.html;
    }
}

第二种实现方式:

  • 编译 Nginx 时需要添加该模块 --with-http_auth_request_module
  • 该模块可以将客户端输入的用户名、密码 username:password 通过 Base64 编码后写入 Request Headers 中
  • 例如:zhang:123456 -> Authorization:Basic d2FuZzp3YW5n=
  • 然后通过第三方程序解码后跟数据库中用户名、密码进行比较,Nginx 服务器通过 header 的返回状态判断是否认证通过。

使用:

server {
    listen 80;
    server_name local.server.com;

    auth_request /auth;

    location / {
        root   html;
        index  index.html;
    }

    location /auth {
        proxy_pass http://auth.gsplovedss.xyz/AuthRequestServer.php;
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
        proxy_set_header X-Original-URI $request_uri;
    }
}

AuthRequestServer.php的代码如下:

<?php

if(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])){
    $username = $_SERVER['PHP_AUTH_USER'];
    $password = $_SERVER['PHP_AUTH_PW'];

    if ($username == 'zhang' && $password == '123456'){
        return true;
    }
}

header('WWW-Authenticate: Basic realm="Auth Server"');
header('HTTP/1.0 401 Unauthorized');