Document updated on Oct 26, 2021
Virtual Hosts
The Virtual Host plugin allows you to run different configurations of KrakenD endpoints based on the host accessing the server.
For instance, you can declare an endpoint /foo that behaves entirely differently when KrakenD is accessed through a host-a.tld or a host-b.tld. For instance, the same /foo path can have different rate limits or authorization endpoints depending on the called host.
Virtual host configuration
To add virtual hosts add the plugin entry that registers Enterprise plugins and the plugin/http-server with the name virtualhost, as depicted below:
{
"version": 3,
"plugin": {
"pattern":".so",
"folder": "/opt/krakend/plugins/"
},
"extra_config": {
"plugin/http-server": {
"name": ["virtualhost", "some-other-plugin" ],
"virtualhost": {
"hosts": ["host-a.tld", "host-b.tld"]
}
}
}
}The configuration keys of this plugin are stored under virtualhost as follows:
Fields of VirtualHost
hosts* array- All recognized virtual hosts by KrakenD must be listed here. The values declared here must match the content of the
Hostheader when passed by the client.Example:["api-a.host.com","api-b.host.com"]
The rest of the boilerplate is the shared part in the configuration for all plugins of the type plugin/http-server. The some-other-plugin in the name array indicates that it can live with other plugins. Delete the entry.
Declaring endpoints
When you enable the virtual host plugin, all requests to KrakenD (/{path}) that match with a recognized host in the list are rewritten internally to /__virtual/{host}/{path}.
Any request to a host that is not declared in the list does not have this redirection.
Virtual host example
Given the following extra_config configuration:
{
"extra_config": {
"plugin/http-server": {
"name": ["virtualhost"],
"virtualhost": {
"hosts": [
"host-a.yourserver.com",
"host-b.yourserver.com"
]
}
}
}
}
And the following endpoints:
{
"version": 3,
"endpoints": [
{
"endpoint": "/foo",
"backend": [
{
"url_pattern": "/__debug/no-host",
"host": ["http://localhost:8080"]
}
]
},
{
"endpoint": "/__virtual/host-a.yourserver.com/foo",
"backend": [
{
"url_pattern": "/__debug/host-A",
"host": ["http://localhost:8080"]
}
]
},
{
"endpoint": "/__virtual/host-b.yourserver.com/foo",
"backend": [
{
"url_pattern": "/__debug/host-B",
"host": ["http://localhost:8080"]
}
]
}
]
}
You can check how /foo hits different endpoints in the following order:
curl -i -H 'Host: anything' http://localhost:8080/foo: No rewriting placed ashostis unknown. Hits the first endpoint.curl -i -H 'Host: host-a.yourserver.com' http://localhost:8080/foo: Hits the second endpointcurl -i -H 'Host: host-b.yourserver.com' http://localhost:8080/foo: Hits the third endpoint
