URL shortening using UUID while serving files ngin

2019-05-21 01:03发布

问题:

Using Django2 and nginx, users can upload files (mainly pic,vids) and I want to serve those files by masking the full url path.

This is the example structure I expect to see but I don't want users to know about this structure or even the image filename.

domain.com/media/user/pictures/Y/M/D/image1.jpg

I want the user to see the above image through a url like this and the random UUID number changes for each file and that number can point to any type of file.

domain.com/media/23kj23l9ak3

When the file is uploaded the original name, permissions assigned (public, friends, private), file path and the UUID that is generated stored in the database) but the file is stored on the filesystem or remote location.

I've never got to this point before and I would like to know what the modern way of doing it would be or let me know what technology/features of django/nginx can help me solve it.

回答1:

I'm not entirely sure why you want to do this, rather than simply using the UUID as the filename of the uploaded file, but you certainly can do it.

One good way would be to route the request via Django, and use the custom X-Accel-Redirect header to tell nginx to respond with a specific file. You would need to store both the UID and the actual path in a Django model. So the nginx config would be something like:

location /protected/ {
  internal;
  alias   /media/user/; # note the trailing slash
}

and the Django view would be:

def user_picture(request, uuid):
    image = MyModel.objects.get(uuid=uuid)
    response = HttpResponse(status=200)
    response['X-Accel-Redirect'] = '/protected/' + image.file.path
    return response


标签: django nginx