Mapping two MEDIA_URLs to the same MEDIA_ROOT

2019-08-26 09:36发布

问题:

I’m migrating a website from WordPress to Django/Wagtail. I have all the old WP content in my media directory & it’s all being served appropriately.

It would be convenient to map other URLs (specifically /wp-content/) to MEDIA_ROOT, for the sake of old media URLs that were hardcoded in the content.

So for example a migrated asset now available at //example.com/media/uploads/2017/12/IMG_2120.jpg can also be served from //example.com/wp-content/uploads/2017/12/IMG_2120.jpg

I’m sure there’s some obvious way to do this (in urls.py?) but totally drawing a blank.

回答1:

I'm sure you already know that static/media files should be served using a frontend server (like Nginx), because it's been mentioned at so many places in the docs.

So, if Django doesn't serve the files, why does it need the MEDIA_ROOT and MEDIA_URL settings?

MEDIA_ROOT is the place where Django stores the images/files you upload.

MEDIA_URL is used by Django to generate file urls. For example, if MEDIA_URL = '/media/', then if you do {{ image.url }}, Django will generate a url like this - /media/image.jpg.

But Django doesn't serve the files. Your frontend server does. So, what you do is, you configure your frontend server like this:

if request path starts with /media/:
    map it to <media directory>

Basically, you're telling your frontend server to serve content from the <media directory> for every request that starts with /media/. This way, a request starting with /media/ never actually reaches your Django app, because your server is taking care of them.

What I mean by all this is that you can configure your frontend server to map /wp-content/uploads/ to your <media directory> and it will serve the files.