How to change media url in django while serving media files using apache2?

Viewed 40

I have a website in production that serves media files properly.

Media Setting in settings.py file :

MEDIA_URL = 'media/'    
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

I have created a media folder inside my project where my all media are being stored. Due to the media URL it severs media files as https://domain_name/media/file_name.

I want to serve my media files as https://domain_name/images/file_name.

I try to change the MEDIA_URL setting in settings.py file, but it shows 404 error for the images.

Updated settings.py file

MEDIA_URL = 'images/'    
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

I am using apache2 as a webserver. Apache file setting:

Alias /static /path_to_the_project/static
  <Directory /path_to_the_project/static>
      Require all granted
  </Directory>


Alias /media /path_to_the_project/media
        <Directory /path_to_the_project/media>
               Require all granted
        </Directory>

  Alias /media /path_to_the_project/images
        <Directory /path_to_the_project/images>
               Require all granted
        </Directory>

<Directory /path_to_the_project/clorrr_tailors>
        <Files wsgi.py>
            Require all granted
        </Files>
      </Directory>

And In template am accessing the images as :

<img src="{{object.image.url}}">
1 Answers

As per the documentation

MEDIA_ROOT is the Absolute file path to the directory that will hold user-uploaded files.

MEDIA_URL on the other hand is a placeholder for the url a client should hit to access your media.

So in your case MEDIA_URL is 'images/' that means url will be pointed to images to access the data in MEDIA_ROOT ie the directory media in your BASE Directory

Related