nginx 内部重定向下载文件
客户端访问下载接口后,先由 flask 处理,进行权限校验等,再重定向到 nginx 下载接口;
在响应头中增加X-Accel-Redirect
配置,nginx 内部重定向
flask 代码
| @app.route("/download_pack") |
| def download_pack() |
| """ |
| 业务处理,权限判断等 |
| """ |
| headers = { |
| 'X-Accel-Redirect': f'/packages/{package_name}', |
| 'X-Accel-Buffering': 'yes', |
| 'Content-Type': 'application/octet-stream', |
| 'Content-Disposition': f'attachment; filename={package_name}' |
| } |
| ret = make_response('', 200, headers) |
| return ret |
nginx 中配置
| |
| #user nobody; |
| worker_processes 1; |
| |
| #error_log logs/error.log; |
| #error_log logs/error.log notice; |
| #error_log logs/error.log info; |
| |
| #pid logs/nginx.pid; |
| events { |
| worker_connections 1024; |
| } |
| |
| |
| http { |
| include mime.types; |
| default_type application/octet-stream; |
| |
| #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' |
| # '$status $body_bytes_sent "$http_referer" ' |
| # '"$http_user_agent" "$http_x_forwarded_for"'; |
| |
| #access_log logs/access.log main; |
| sendfile on; |
| #tcp_nopush on; |
| |
| #keepalive_timeout 0; |
| keepalive_timeout 65; |
| |
| #gzip on; |
| upstream flask-server { |
| server 127.0.0.1:8000; |
| } |
| server { |
| listen 80; |
| server_name localhost; |
| server_tokens off; |
| # flask 负责接口 |
| location / { |
| proxy_pass http://flask-server; |
| proxy_redirect off; |
| proxy_set_header X-Real-IP $remote_addr; |
| proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; |
| } |
| # 内部重定向下载接口 |
| location /packages { |
| internal; # 内部接口 |
| alias /packages; |
| } |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)