Nginx,Gunicorn和Django的静态文件权限

前端之家收集整理的这篇文章主要介绍了Nginx,Gunicorn和Django的静态文件权限前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我尝试使用运行Django的Gunicorn WSGI服务器设置Nginx服务器.

设置似乎都运行,除了我有权限问题.我已经为/ media和/ static目录设置别名以提供静态内容,但是除非文件Nginx用户所有,否则会生成403错误.

Gunicorn用户上传文件显然属于该特定用户所有,这将导致问题.我可以将Nginx用户添加到gunicorn用户组,但是我不想给这些文件赋予Nginx一揽子权限.

通过Gunicorn / Wsgi / Django上传生成文件的建议方法是什么,但允许Nginx在不增加安全性问题的情况下为它们提供服务.

提前致谢,

最佳答案
不需要对这些文件的一揽子权限. Nginx只需要一个读取权限.我的Nginx用户帐户是www-data,gunicorn以www_flask权限运行. Nginx提供从flask上传的所有文件没有问题.

文件权限ls -lRr / webroot

/webroot:
total 4
drwxr-xr-x 3 www_flask www_flask 4096 Jul  4 13:20 gunicorn

/webroot/gunicorn:
total 4
drwxr-xr-x 2 www_flask www_flask 4096 Jul  4 14:57 uploads

/webroot/gunicorn/uploads:
total 924
-rw-rw-r-- 1 www_flask www_flask 164308 Jul  4 14:55 0001.jpg
-rw-rw-r-- 1 www_flask www_flask  53917 Jul  4 14:56 0004.jpg
-rw-rw-r-- 1 www_flask www_flask 349420 Jul  4 15:07 0005.jpg
-rw-rw-r-- 1 www_flask www_flask 365642 Jul  4 14:56 0006.jpg

Nginx配置

server {
    listen 127.0.0.1:80;
    server_name localhost;

    location / { 
        try_files $uri @gunicorn_proxy; 
    }   

    location /media {
        alias /webroot/gunicorn/uploads/;
    }   

    location @gunicorn_proxy {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:8000;
    }   
}

来自教程/home/www_flask/evironments/flask/myapp/myapp.py的Flask上传示例

import os
from flask import Flask,request,redirect,url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = '/webroot/gunicorn/uploads'

ALLOWED_EXTENSIONS = set(['txt','pdf','png','jpg','jpeg','gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS

def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],filename)

@app.route('/',methods=['GET','POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
            return redirect('media/' + filename)
    return '''
    
原文链接:https://www.f2er.com/nginx/435381.html

猜你在找的Nginx相关文章