当前位置: 首页 > news >正文

Nginx IP授权页面实现步骤

目标:

一、创建白名单文件

sudo mkdir -p /usr/local/nginx/conf/whitelist
sudo touch /usr/local/nginx/conf/whitelist/temporary.conf

二、创建Python认证服务

文件路径:/opt/script/auth_server.py

import os
import time
from flask import Flask, request, abort
import sysapp = Flask(__name__)# 配置参数
USERS = [{"username": "admin1", "password": "111111"},{"username": "admin2", "password": "222222"}
]
TEMP_CONF = "/usr/local/nginx/conf/whitelist/temporary.conf"
IP_LOG = "/usr/local/nginx/conf/whitelist/ip_time.log"  # 存储IP和添加时间def update_whitelist():"""更新临时白名单文件"""current_time = time.time()valid_ips = []# 读取所有IP并过滤过期项if os.path.exists(IP_LOG):with open(IP_LOG, "r") as f:for line in f.readlines():parts = line.strip().split()if len(parts) == 2:ip, timestamp = partsif current_time - float(timestamp) < 7200:  # 2小时=7200秒valid_ips.append(ip)# 生成新的白名单配置with open(TEMP_CONF, "w") as f:for ip in set(valid_ips):  # 去重f.write(f"allow {ip};\n")# 重载Nginxos.system("sudo /usr/local/nginx/sbin/nginx -s reload")@app.route('/auth', methods=['POST'])
def auth():# 获取客户端提交的凭证submitted_user = request.form.get('user')submitted_pass = request.form.get('pass')# 验证用户名密码 - 支持多个账号authenticated = Falsefor user in USERS:if submitted_user == user["username"] and submitted_pass == user["password"]:authenticated = Truebreakif not authenticated:abort(401)# 获取真实客户端IPclient_ip = request.headers.get('X-Real-IP', request.remote_addr)# 记录IP和当前时间戳with open(IP_LOG, "a") as f:f.write(f"{client_ip} {time.time()}\n")# 更新白名单文件update_whitelist()return "认证成功!您的IP已加入白名单,有效期2小时。", 200if __name__ == '__main__':if len(sys.argv) > 1 and sys.argv[1] == "update":update_whitelist()else:app.run(host='127.0.0.1', port=5000)

三、创建登录页面

文件路径:/usr/local/nginx/html/auth.html

<!DOCTYPE html>
<html>
<head><title>访问授权</title>
</head>
<body><h2>请输入管理员凭据</h2><form action="/auth" method="POST"><label>用户名: <input type="text" name="user"></label><br><label>密码: <input type="password" name="pass"></label><br><button type="submit">授权我的IP</button></form>
</body>
</html>

四、配置Nginx

nginx.confhttp块内添加:

server {listen 80;server_name your_domain.com;  # 改为你的域名或IP# 授权页面location = /auth.html {alias /usr/local/nginx/html/auth.html;}# Python认证服务代理location = /auth {proxy_pass http://127.0.0.1:5000/auth;proxy_set_header X-Real-IP $remote_addr;  # 传递真实IP}# 需要保护的资源location /protected {if ($whitelist = 0) {return 302 /auth.html;  # 重定向到登录页}# 这里放被保护的内容(例如反向代理)# proxy_pass http://your_backend;}
}

五、设置定时清理任务

创建清理脚本:/usr/local/nginx/scripts/clean_whitelist.py

#!/usr/bin/env python3
import os
import time
import sysIP_LOG = "/usr/local/nginx/conf/whitelist/ip_time.log"def main():# 读取并过滤过期IPvalid_entries = []current_time = time.time()if not os.path.exists(IP_LOG):returnwith open(IP_LOG, "r") as f:for line in f:parts = line.strip().split()if len(parts) == 2:ip, timestamp = partsif current_time - float(timestamp) < 7200:  # 保留未过期IPvalid_entries.append(line)# 更新日志文件with open(IP_LOG, "w") as f:f.writelines(valid_entries)# 调用认证服务更新白名单os.system("sudo /usr/bin/python3 /usr/local/nginx/scripts/auth_server.py update")if __name__ == '__main__':main()

 添加cron任务

# 添加cron任务
sudo crontab -e
# 每10分钟检查一次
*/10 * * * * /usr/bin/python3 /opt/script/clean_whitelist.py

六、启动服务

启动Python认证服务:

sudo pip3 install flask
sudo -b nohup python3 auth_server.py > /var/log/auth_server.log 2>&1

重载Nginx配置:

sudo /usr/local/nginx/sbin/nginx -s reload

七、验证功能

  1. 访问 http://your_domain.com/protected

  2. 将被重定向到登录页

  3. 输入用户名 admin1 和密码 111111

  4. 成功后:

    • 你的IP会被添加到 temporary.conf

    • 可访问 /protected 资源

    • 2小时后IP自动删除

注意

# 确保所有脚本有执行权限
chmod +x /opt/script/*.py


文章转载自:
http://forme .hfytgp.cn
http://thalloid .hfytgp.cn
http://zebec .hfytgp.cn
http://arachnology .hfytgp.cn
http://tabernacle .hfytgp.cn
http://maritsa .hfytgp.cn
http://religiosity .hfytgp.cn
http://idleness .hfytgp.cn
http://dilaceration .hfytgp.cn
http://sensibility .hfytgp.cn
http://plantmilk .hfytgp.cn
http://gaw .hfytgp.cn
http://alleynian .hfytgp.cn
http://lampless .hfytgp.cn
http://sumac .hfytgp.cn
http://drastically .hfytgp.cn
http://wga .hfytgp.cn
http://stylistician .hfytgp.cn
http://aforenamed .hfytgp.cn
http://chesapeake .hfytgp.cn
http://saurian .hfytgp.cn
http://sanctified .hfytgp.cn
http://cystoma .hfytgp.cn
http://subcompact .hfytgp.cn
http://hamal .hfytgp.cn
http://oofy .hfytgp.cn
http://underwriting .hfytgp.cn
http://inorganized .hfytgp.cn
http://dislikeable .hfytgp.cn
http://parka .hfytgp.cn
http://www.dtcms.com/a/290868.html

相关文章:

  • Grok网站的后端语言是php和Python2.7
  • Python 变量赋值与切片语法(in-place 修改 vs 重新赋值)
  • 《画布角色的双重灵魂:解析Canvas小游戏中动画与碰撞的共生逻辑》
  • 状压DP学习笔记[浅谈]
  • 计算机网络:概述层---计算机网络的性能指标
  • IFN影视官网入口 - 4K影视在线看网站|网页|打不开|下载
  • 算法训练营DAY37 第九章 动态规划 part05
  • Linux开发⊂嵌入式开发
  • 复制docker根目录遇到的权限问题
  • Mac安装Typescript报错
  • macOS 上安装 Kubernetes(k8s)
  • 深度学习-常用环境配置
  • 基于R语言的分位数回归技术应用
  • next.js刷新页面时二级菜单展开状态判断
  • Java 通过 HttpURLConnection发送 http 请求
  • CG-04 翻斗式雨量传感器 分辨率0.1mm,0.2mm可选择 金属材质
  • 数据结构自学Day11-- 排序算法
  • 使用 Longformer-base-4096 进行工单问题分类
  • Redis进阶--缓存
  • Ubuntu 22.04 安装 MySQL 8.0 完整步骤文档
  • 计算机网络中:传输层和网络层之间是如何配合的
  • 7月21日星期一今日早报简报微语报早读
  • 计算机史前时代:从原始计数到机械曙光
  • 计算机发展史:集成电路时代的微缩革命
  • Android 实例 - 分页器封装实现(上一页按钮、下一页按钮、当前页码 / 总页数、每页条数、总记录数)
  • 本地部署AI新选择!LocalAI+cpolar轻松实现隐私安全的远程访问
  • 数据结构:找出字符串中重复的字符(Finding Duplicates in a String)——使用哈希表
  • 一文彻底解释清楚Java 中的NIO、BIO和AIO
  • 记录解决问题--maven本地已有依赖,还是去远程仓库下载,导致打包失败
  • 期权到期会对大盘有什么影响?