mime-typeshttpservercontent-dispositioncaddycaddyfile

Caddy2: how to set MIME type and Content-disposition for a file extension?


What is the way to configure/override how certain MIME types are handled?

For example, with the default configuration a python file (.py) is served with Content-disposition": attachment which opens a file save dialog rather than displaying inline plain text in the browser.

I've identified one possible approach:

@py {
    path *.py
}

header @py Content-Type text/plain

While this works, it looks more of a hack rather than adding/modifying a mime type, given that it's simply setting a header based on a substring match. Is this the only possible approach?

What defines that a specific MIME type should be served inline or have "Content-disposition": attachment? Does caddy expose a straightforward way to configure how MIME types are handled?

The correct mime type for .py files is application/x-python-code or text/x-python. How can I configure caddy to treat these types as inline plain text, and not add the Content-disposition": attachment header? Forcing text/plain works as a workaround, but I am assuming there is a cleaner way to do it.

Update: on further perusal of caddy docs it appears that caddy relies on go's rather limited set of MIME types, which are then further extended with OS-specific global MIME types from e.g. /etc/mime.types, /etc/apache2/mime.type, etc, or from the registry if on windows.


Solution

  • Updated Response

    Thanks @ccpizza

    You can do this a lot nicer by applying some regex to the extension matching. Also, specifying the mime type is not necessary if the default is correct. So something like this works just as well:

    example.com {
        root * "/path/to/files/"
    
        @inlineFiles {
            path ^.*\.(py|mp4|ps1)$
        }
        header @inlineFiles {
            Content-Disposition inline
        }
    
        file_server {
            browse
        }
    }
    



    Old Response

    Try something like this

    doma.in {
        root * "/path"
    
        @py {
            path *.py
        }
        header @py {
            Content-Type text/x-python
            Content-Disposition inline
        }
    
        file_server {
            browse
        }
    }
    

    If you would like to add mp4 files for example just add another block like this:

    @mp4 {
        path *.mp4
    }
    header @mp4 {
        Content-Type video/mp4
        Content-Disposition inline
    }