Nginx auth_request通过unix:sock进行处理
前面文章介绍了python作为nginx的认证或者其他预处理,http://www.cnblogs.com/inns/p/6568131.html
采用TCP方式实现,本文使用unix:sock优化
Nginx的配置
location /fileviewfdfs/
{
auth_request /ncgi.py;
auth_request_set $url $sent_http_url;
proxy_pass $url;
}
#/ncgi.py
location ~/ncgi.py$ {
# fastcgi_pass 127.0.0.1:50001;
fastcgi_pass unix:/tmp/python-cgi.sock;
fastcgi_param REQUEST_URI $request_uri;
include fastcgi_params;
}
ncgi.py代码
# -*-coding:utf-8-*-
"""
提供给 Nginx 加密的URL解密接口
Author:yinshunyao
Date:2017/3/17 0017上午 11:00
"""
from flup.server.fcgi import WSGIServer
import re
import os
# from Prpcrypt import prpcrypt
import pwd
# p = prpcrypt()
_port = '8999'
_user = "www-data"
_group = "www-data"
# 查询配置值
def _find_value(name,config_content):
value_info = re.search('{}=(.*)'.format(name), config_content)
if not value_info:
raise Exception('{}配置不存在'.format(name))
return value_info.groups()[0].strip()
# 加载配置
def _refresh_config():
current_path = os.path.abspath(os.path.dirname(__file__))
with open('{}/ncgi.ini'.format(current_path), 'r') as config:
content = config.read()
global _port, _user, _group
_port = _find_value('port', content)
_user = _find_value('user', content)
_group = _find_value('group', content)
# 获取group的id
def _get_group_id(name):
try:
output = os.popen('cat /etc/group')
group_info = output.read()
value_info = re.search('{}:(.*)'.format(name), group_info)
return value_info.groups()[0].split(':')[1]
except:
raise Exception('获取group id失败')
def parse_ip(environ, start_response):
request_uri = environ.get('REQUEST_URI') or ''
# print 'request_uri', request_uri
splits = request_uri.split('/')
if len(splits) < 4:
# print('unknow url:{}'.format(request_uri))
start_response('500 Error URL', [])
else:
# 格式 splits
# ['', 'fileviewfdfs', '2fca4d0a2f906be8ef669eee42a888ec', 'group1', 'M00', '00', '00', 'wKgA4Vnqo1iAL3WwAABUAGSh7FI951.xls']
try:
# 去掉fileviewfdfs,可以做认证
url = 'http://{}:{}/{}'.format(splits[2], _port, '/'.join(splits[3:]))
# print('url:{}'.format(url))
start_response('200 OK', [('url', url)])
except Exception, e:
print('parse the IP error:{}'.format(e))
start_response('500 Error for parse the URL', [])
return ['']
if __name__ == '__main__':
# 刷新配置
_refresh_config()
group_id = _get_group_id(_group)
print '存储端口配置 {}'.format(_port)
print '运行用户组{},用户组id{},用户{}'.format(_group, group_id, _user)
# 切换配置文件用户组
os.setegid(int(group_id))
os.setuid(pwd.getpwnam(_user).pw_uid)
# WSGIServer(parse_ip, bindAddress=('127.0.0.1', cgi_port)).run()
WSGIServer(parse_ip, bindAddress='/tmp/python-cgi.sock').run()
好记性不如烂笔头