Cant get caddy to server django media files

1. Caddy version (caddy version):

caddy:2.2.1-alpine

2. How I run Caddy:

I run it with docker swarm. Caddy, django and postges are all in a docker-compose file

version: "3.7"

services:
  caddy:
    image: caddy:2.2.1-alpine
    ports:
      - 8000:8000
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
      - caddy_data:/data
      - caddy_config:/config
      - media_volume:/app/media

  web:
    image: ""
    deploy:
      restart_policy:
        condition: on-failure
    environment:
      - ENVIRONMENT=deployment
      - ALLOWED_HOSTS=localhost 127.0.0.1 10.0.2.15 web
      - SECRET_KEY= ***
      - GOOGLE_BOOK_API= ***
      - TMDB_KEY= ***
      - NYT_API= ***
      - DEBUG=0
      - ZOHO_HOST= ***
      - ZOHO_USER= ***
      - ZOHO_PASS= ***
      - SQL_ENGINE=django.db.backends.postgresql_psycopg2
      - SQL_DB= ***
      - SQL_USER= ***
      - SQL_PASSWORD= ***
      - SQL_HOST=db
      - SQL_PORT=5432
    volumes:
      - media_volume:/app/media
      - static_volume:/app/staticfiles
    depends_on:
      - db

  db:
    image: postgres:12.1
    deploy:
      restart_policy:
        condition: on-failure
    environment:
      - POSTGRES_DB= ***
      - POSTGRES_USER= ***
      - POSTGRES_PASSWORD= ***
      - POSTGRES_HOST=db
    volumes:
      - postgres_data:/var/lib/postgresql/data/

volumes:
  postgres_data:
  caddy_config:
  caddy_data:
  media_volume:
  static_volume:

a. System environment:

I am running on windows 10 with docker

d. My complete Caddyfile or JSON config:

http://localhost:8000 {
    @notStatic {
        not path /media/*
    }

    root * ./medialogbook/media/

    reverse_proxy @notStatic web:8000

    file_server 
}

3. The problem I’m having:

I am unable to get caddy to server my media images. I followed some other guides and got to my current caddyfile config, but it still is not working.

Caddy’s file_server takes the root and appends the path to it, so it’ll be looking in ./medialogbook/media/media/foo for your files, with your current config.

You could do it this way:

http://localhost:8000 {
	handle_path /media* {
		root * ./medialogbook/media
		file_server
	}

	reverse_proxy web:8000
}

The handle_path directive will strip the given path prefix from the request before continuing, so it solves that appending issue.

You can also get rid of the not path matcher here because the Caddyfile will sort handle_path before reverse_proxy as per the directive order:

Thank you very much I was able to get it working

1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.