Evgenii Legotckoi
Evgenii LegotckoiSept. 12, 2023, 2:47 a.m.

Django - Protected media content

On one of the resources that I am developing, there was a need to add protected access to media content, checking the user's right to access this media content. Simply put, can the user view the photo that nginx serves as static content.

In fact, in the case of nginx and django, everything is much simpler than it seems at first glance.

Let's look at this using the example of uploading and uploading a photo.

Algorithm for working with photography

  • Uploading a photo to a special protected directory
  • An attempt to get a photo via a direct url to a photo or in a website page (for example, an img tag)
  • Checking photo permissions
  • Creating a redirect in nginx to an internal protected directory on the server
  • Receiving a photo

Everything seems simple, but now let's see what is required for this.


Let's set up the site's django configuration file. Usually, to download media content and automatically serve it via nginx, something similar is written in the settings.

MEDIA_ROOT = BASE_DIR.parent / 'media'
MEDIA_URL = '/media/'

However, this time we are using a special protected directory, which I always call protected .

MEDIA_ROOT = BASE_DIR.parent / 'protected'
MEDIA_URL = '/media/'

Thus, we say that in the external space we have "media" , and in the dark halls of the server it is "protected" .

Such code might correspond to the following directory structure.

  • /home/www/django_project_root_folder - this is the main directory where the project, static and honey directories, as well as the virtual environment are located
  • /home/www/django_project_root_folder/protected - protected media directory
  • /home/www/django_project_root_folder/static - directory with static content
  • /home/www/django_project_root_folder/django_project - your django application
  • /home/www/django_project_root_folder/python_venv - virtual environment

I currently like this structure, because if the python version changes, that is, the virtual environment is updated, you can simply initialize the new environment and change a couple of lines in the configuration so that the site application is launched from the new virtual environment. In this case, neither the project repository, nor static files, nor media content will be affected.

Configuration nginx

I will give a small piece of configuration that is directly responsible for setting up nginx access to the protected directory

 server {

     # Other code

     location /protected/ {
        root /home/www/django_project_root_folder/;
        expires 30d;

With this code we simply indicate where the protected directory is located and that it is internal, that is, the user will not simply receive its contents without special permission.

Uploading photos

To work with photographs, I currently use this data model, of course with modifications for a specific project, but the basis is the same

# -*- coding: utf-8 -*-

import os
import uuid

from django.contrib.gis.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _

from photo.fields import WEBPField
from photo.managers import PhotoManager

def image_folder(instance, filename):
    return 'photos/{}.webp'.format(uuid.uuid4().hex)

class Photo(models.Model):
    class Meta:
        verbose_name = _('Photo')
        verbose_name_plural = _('Photos')

    created_at = models.DateTimeField(verbose_name=_('Created at'), auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name=_('Updated at'), auto_now=True)
    height = models.IntegerField(verbose_name=_('Height'), default=0, blank=True, null=True)
    width = models.IntegerField(verbose_name=_('Width'), default=0, blank=True, null=True)
    image = WEBPField(

    def filename(self):
        return os.path.basename(self.image.name)

@receiver(post_delete, sender=Photo)
def auto_delete_image_on_delete(sender, instance, **kwargs):
    if instance.image:
        if os.path.isfile(instance.image.path):

A special field WEBPField is used here, which I have already talked about. This is a field that converts an image to webp format on the fly. There is also code for automatically deleting photos from the server. But this is not the most important thing.

The most important thing is this function

def image_folder(instance, filename):
    return 'photos/{}.webp'.format(uuid.uuid4().hex)

This function generates a file name and indicates where to save the file on the server relative to the protected directory.

As a result, the photo will be saved in the following path


In this case, the code for the img tag in the template will look like this:

<img src="{{ photo.image.url }}"/>

And the result will look like this

<img src="/media/photos/0aec484a6ff246d7ad5eb1b06c0a698e.webp"/>

## urls.py

I'll start by specifying the url manager to access the content

# -*- coding: utf-8 -*-

from django.urls import path

from photo.views import photo_access

urlpatterns = [
    path('media/photos/<str:path>', photo_access, name='photo'),

As you can see, here is a url that matches the result for the img tag.

Function photo_access

And now the most interesting thing is how exactly access to protected content is carried out

# -*- coding: utf-8 -*-

from django.http import HttpResponse, HttpResponseForbidden

from photo.models import Photo
from utils.shortcuts import get_object_or_none

def photo_access(request, path):
    def create_x_accel_redirect(path):
        response = HttpResponse()
        # Content-type will be detected by nginx
        del response['Content-Type']
        response['X-Accel-Redirect'] = '/protected/photos/' + path
        return response

    photo = get_object_or_none(Photo, image='photos/' + path)
    if photo is None:
        return HttpResponseForbidden('Not authorized to access this media.')

    # Some another check code
    if condition is True:
        return create_x_accel_redirect(path)

    if request.user.is_authenticated and request.user.is_staff:
        return create_x_accel_redirect(path)

    return HttpResponseForbidden('Not authorized to access this media.')

In this function, we check whether the user is an authorized representative of the resource administration and whether the photo object exists. You can also add any other conditions you like.

If they are executed, then using the create_x_accel_redirect function we add a directive that redirects the request inside nginx to the image.

That is, we replace /media/photos/0aec484a6ff246d7ad5eb1b06c0a698e.webp with /protected/photos/0aec484a6ff246d7ad5eb1b06c0a698e.webp and redirect the request with the X-Accel-Redirect directive.
Thus, nginx serves content from a protected directory via media url.

More details about the X-Accel-Redirect directive can be found on the official nginx wiki

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!


Only authorized users can post comments.
Please, Log in or Sign up

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1

C++ - Тест 003. Условия и циклы

  • Result:92points,
  • Rating points8
  • dsfs
  • April 26, 2024, 11:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
Last comments
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
George13May 7, 2024, 7:27 a.m.
добавить qlineseries в функции в функции: "GPlotter::addSeries(QString title, QVector &arr)" я вызываю метод setChart(...), я в конструктор передал адрес на QChartView элемент
BlinCTMay 5, 2024, 12:46 p.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
Peter SonMay 4, 2024, 12:57 a.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 2, 2024, 9:07 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderCheApril 30, 2024, 11:22 a.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks