Skip to content

Instantly share code, notes, and snippets.

@bartolli
Last active May 16, 2025 13:51
Show Gist options
  • Select an option

  • Save bartolli/0ebd16d4770118c37cbdbe87b59d4f01 to your computer and use it in GitHub Desktop.

Select an option

Save bartolli/0ebd16d4770118c37cbdbe87b59d4f01 to your computer and use it in GitHub Desktop.
Caddy server to securely authenticate and proxy requests to a local Ollama instance, utilizing environment-based API key validation for enhanced security.
# /opt/homebrew/etc/Caddyfile
http://localhost:8080 {
# Define a matcher for authorized API access
@apiAuth {
header Authorization "Bearer {env.OLLAMA_API_KEY}"
}
# Proxy authorized requests
reverse_proxy @apiAuth http://localhost:11434 {
header_up Host {http.reverse_proxy.upstream.hostport}
}
# Define a matcher for unauthorized access
@unauthorized {
not {
header Authorization "Bearer {env.OLLAMA_API_KEY}"
}
}
# Respond to unauthorized access
respond @unauthorized "Unauthorized" 401 {
close
}
}
# This test should fail, resulting in a 401 Unauthorized response.
curl -i http://localhost:8080 -H "Authorization: Bearer wrong_api_key"
# This test should succeed if everything is configured correctly.
# Replace correct_api_key with the actual value you’ve set for OLLAMA_API_KEY.
curl -i http://localhost:8080 -H "Authorization: Bearer correct_api_key"
# Test Ollama
curl http://localhost:8080/api/generate -H "Authorization: Bearer correct_api_key" -d '{
"model": "llama3:8b",
"prompt": "Why is the sky blue?",
"stream": false
}'
export OLLAMA_API_KEY="actual_api_key_here"
source ~/.zshrc
brew services start caddy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment