目录
1. 安装nginx
- 从 Nginx 1.5.4 版本开始,ngx_http_auth_request_module 已经被合并到 Nginx 的主线代码库中,因此不需要单独下载和编译这个模块。如果你使用的是 Nginx 的官方版本并且版本号在 1.5.4 或以上,那么这个模块应该已经可用。
- 查看当前nginx是否包含ngx_http_auth_request_module
nginx -V
如果显示 --with-http_auth_request_module 则成功,否则执行下面操作
1.1 nginx不包含ngx_http_auth_request_module
1.1.1 源码安装
- 重新编译 Nginx: 如果你需要 ngx_http_auth_request_module 模块,那么你可能需要重新编译 Nginx。以下是基本步骤:
- 首先,安装 Nginx 的源代码包,通常可以通过包管理器或直接从 Nginx 官网下载。
- 在编译 Nginx 时,确保包含 --with-http_auth_request_module 配置选项。以下是一个编译命令的例子:
######################
/configure --prefix=/usr/local/nginx --with-http_auth_request_module …
make
sudo make install
######################- 替换 … 为其他你可能需要的配置选项。
1.1.2 yum安装
sudo yum remove nginx # 卸载Nginx
sudo yum autoremove nginx # 清除配置文件
sudo yum install nginx # 重新安装Nginx
2. 配置nginx
server {
listen 443 ssl; # 监听端口(前端访问端口)
server_name 127.0.0.1; # IP或者域名(前端访问)
charset utf-8;
client_max_body_size 75M;
ssl_certificate /etc/nginx/server.crt; # 必须nginx.conf同级
ssl_certificate_key /etc/nginx/server.key; # 必须nginx.conf同级
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://127.0.0.1:8000/; # gunicorn的bind
proxy_set_header Host $host:443;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 3600;
proxy_send_timeout 3600;
proxy_read_timeout 3600;
send_timeout 3600;
}
location /static/ { #这里做了访问静态目录不走uwsgi/gunicorn
alias /home/kmsj845/cbs/seqauto/static/;
}
location /log_files/ {
auth_request /auth-log-files/; # 走的是第一个location中的认证接口
alias /home/kmsj845/seqauto/log/; # 指向的目录
error_page 401 = @login_redirect; # 认证失败执行的location
autoindex on;
default_type text/html;
types {
text/plain log;
text/plain sh;
}
}
location @login_redirect {
set $original_uri $uri;
if ($arg_next) {
set $original_uri $arg_next;
}
return 302 /admin/login?next=$original_uri; # 重定向到登录页,走的是第一个location中的接口
}
}
3. django api
3.1 views.py
def auth_log_files(request):
try:
if request.user.is_authenticated:
return HttpResponse('', status=200)
except Exception as e:
pass
return HttpResponse('', status=401)
3.2 urls.py
path("auth-log-files/", views.auth_log_files, name="auth_log_files"),
3.3 middleware.py
如果不修改,则无法从登录页正常跳转到期望页
class ModifyNextMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.path.startswith('/admin/login'):
next_url = request.GET.get('next', '')
if 'next=' in next_url: # next_url中还包含next
real_next_url = next_url.split('next=')[-1]
request.GET = request.GET.copy()
request.GET['next'] = real_next_url
response = self.get_response(request)
return response
3.4 settings.py
...
MIDDLEWARE = [
...
'YOUR_APP.middleware.ModifyNextMiddleware',
...
]
...