Search code examples
aliascaddyfile

alias a single file in caddy?


I want to serve a simple folder as website and then, in a subfolder, I wan to serve a few specific files from another root location (not the whole folder, just a few files).

Sadly, this does not work:

localhost {
    header {
        Cache-Control "no-cache, no-store, must-revalidate"
    }

    tls C:\localhost\keys\localhost.crt C:\localhost\keys\localhost.key
    log {
        output file C:\localhost\logs\access.log
        format console
    }

    handle_path /js/main.js {
        # THIS DOES NOT WORK
        root "C:\someOtherFolder\main.js"
    }

    handle {
        # handle base www folder
        file_server browse
        root * "C:\localhost\www"
    }
}

I want the file https://localhost/js/main.js to serve the file located in C:\someOtherFolder\main.js while the rest of the subfolder /js/ is serving whatever is in C:\localhost\www\js.

In apache I would have used a single line with alias like this:

Alias /js/main.js C:/someOtherFolder/main.js

How can this be done?


Solution

  • You also need to specify it should be handled by file_server:

    handle_path /js/main.js {
        root "C:\someOtherFolder\main.js"
        file_server
    }
    

    If you want to do this for multiple files, one way is to use a named matcher and handle:

    @special_js_files {
      path /js/main.js
      path /js/another.js
    }
    
    handle @special_js_files {
      uri strip_prefix /js
      root "C:\someOtherFolder\"
      file_server
    }
    

    This does require that the filenames in the URI match the filenames in the root directory. Look here for an explanation of uri strip_prefix.