When to use Kestrel with a reverse proxy

You can use Kestrel by itself or with a reverse proxy server, such as IIS, Nginx, or Apache. A reverse proxy server receives HTTP requests from the Internet and forwards them to Kestrel after some preliminary handling.

Either configuration—with or without a reverse proxy server—is a valid and supported hosting configuration for ASP.NET Core 2.0 or later apps.

If an app accepts requests only from an internal network, Kestrel can be used directly as the app's server.

If you expose your app to the Internet, use IIS, Nginx, or Apache as a reverse proxy server. A reverse proxy server receives HTTP requests from the Internet and forwards them to Kestrel after some preliminary handling.

A reverse proxy is required for edge deployments (exposed to traffic from the Internet) for security reasons. The 1.x versions of Kestrel don't have a full complement of defenses against attacks, such as appropriate timeouts, size limits, and concurrent connection limits.

A reverse proxy scenario exists when there are multiple apps that share the same IP and port running on a single server. Kestrel doesn't support this scenario because Kestrel doesn't support sharing the same IP and port among multiple processes. When Kestrel is configured to listen on a port, Kestrel handles all of the traffic for that port regardless of requests' host header. A reverse proxy that can share ports has the ability to forward requests to Kestrel on a unique IP and port.

Even if a reverse proxy server isn't required, using a reverse proxy server might be a good choice:

It can limit the exposed public surface area of the apps that it hosts.

It provides an additional layer of configuration and defense.

It might integrate better with existing infrastructure.

It simplifies load balancing and SSL configuration. Only the reverse proxy server requires an SSL certificate, and that server can communicate with your app servers on the internal network using plain HTTP.

Warning

If not using a reverse proxy with host filtering enabled, host filtering must be enabled.

There's a separate limit for connections that have been upgraded from HTTP or HTTPS to another protocol (for example, on a WebSockets request). After a connection is upgraded, it isn't counted against the MaxConcurrentConnections limit.

An exception is thrown if you attempt to configure the limit on a request after the app has started to read the request. There's an IsReadOnly property that indicates if the MaxRequestBodySize property is in read-only state, meaning it's too late to configure the limit.

Kestrel checks every second if data is arriving at the specified rate in bytes/second. If the rate drops below the minimum, the connection is timed out. The grace period is the amount of time that Kestrel gives the client to increase its send rate up to the minimum; the rate isn't checked during that time. The grace period helps avoid dropping connections that are initially sending data at a slow rate due to TCP slow-start.

The default minimum rate is 240 bytes/second with a 5 second grace period.

A minimum rate also applies to the response. The code to set the request limit and the response limit is the same except for having RequestBody or Response in the property and interface names.

Here's an example that shows how to configure the minimum data rates in Program.cs:

Endpoint configuration

By default, ASP.NET Core binds to http://localhost:5000. Call Listen or ListenUnixSocket methods on KestrelServerOptions to configure URL prefixes and ports for Kestrel. UseUrls, the --urls command-line argument, urls host configuration key, and the ASPNETCORE_URLS environment variable also work but have the limitations noted later in this section.

The urls host configuration key must come from the host configuration, not the app configuration. Adding a urls key and value to appsettings.json doesn't affect host configuration because the host is completely initialized by the time the configuration is read from the configuration file. However, a urls key in appsettings.json can be used with UseConfiguration on the host builder to configure the host:

UseUrls, the --urls command-line argument, urls host configuration key, and the ASPNETCORE_URLS environment variable also work but have the limitations noted later in this section (a default certificate must be available for HTTPS endpoint configuration).

ASP.NET Core 2.1 KestrelServerOptions configuration:

ConfigureEndpointDefaults(Action<ListenOptions>)
Specifies a configuration Action to run for each specified endpoint. Calling ConfigureEndpointDefaults multiple times replaces prior Actions with the last Action specified.

ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions>)
Specifies a configuration Action to run for each HTTPS endpoint. Calling ConfigureHttpsDefaults multiple times replaces prior Actions with the last Action specified.

Configure(IConfiguration)
Creates a configuration loader for setting up Kestrel that takes an IConfiguration as input. The configuration must be scoped to the configuration section for Kestrel.

ListenOptions.UseHttps
Configure Kestrel to use HTTPS.

ListenOptions.UseHttps extensions:

UseHttps – Configure Kestrel to use HTTPS with the default certificate. Throws an exception if no default certificate is configured.

The value provided using these approaches can be one or more HTTP and HTTPS endpoints (HTTPS if a default cert is available). Configure the value as a semicolon-separated list (for example, "Urls": "http://localhost:8000;http://localhost:8001").

Replace the default certificate from configuration

WebHost.CreateDefaultBuilder calls serverOptions.Configure(context.Configuration.GetSection("Kestrel")) by default to load Kestrel configuration. A default HTTPS app settings configuration schema is available for Kestrel. Configure multiple endpoints, including the URLs and the certificates to use, either from a file on disk or from a certificate store.

In the following appsettings.json example:

Set AllowInvalid to true to permit the use of invalid certificates (for example, self-signed certificates).

Any HTTPS endpoint that doesn't specify a certificate (HttpsDefaultCert in the example that follows) falls back to the cert defined under Certificates > Default or the development certificate.

An alternative to using Path and Password for any certificate node is to specify the certificate using certificate store fields. For example, the Certificates > Default certificate can be specified as:

Endpoints names are case-insensitive. For example, HTTPS and Https are valid.

The Url parameter is required for each endpoint. The format for this parameter is the same as the top-level Urls configuration parameter except that it's limited to a single value.

These endpoints replace those defined in the top-level Urls configuration rather than adding to them. Endpoints defined in code via Listen are cumulative with the endpoints defined in the configuration section.

The Certificate section is optional. If the Certificate section isn't specified, the defaults defined in earlier scenarios are used. If no defaults are available, the server throws an exception and fails to start.

The Certificate section supports both Path–Password and Subject–Store certificates.

Any number of endpoints may be defined in this way so long as they don't cause port conflicts.

serverOptions.Configure(context.Configuration.GetSection("Kestrel")) returns a KestrelConfigurationLoader with an .Endpoint(string name, options => { }) method that can be used to supplement a configured endpoint's settings:

You can also directly access KestrelServerOptions.ConfigurationLoader to keep iterating on the existing loader, such as the one provided by WebHost.CreateDefaultBuilder.

The configuration section for each endpoint is a available on the options in the Endpoint method so that custom settings may be read.

Multiple configurations may be loaded by calling serverOptions.Configure(context.Configuration.GetSection("Kestrel")) again with another section. Only the last configuration is used, unless Load is explicitly called on prior instances. The metapackage doesn't call Load so that its default configuration section may be replaced.

KestrelConfigurationLoader mirrors the Listen family of APIs from KestrelServerOptions as Endpoint overloads, so code and config endpoints may be configured in the same place. These overloads don't use names and only consume default settings from configuration.

Change the defaults in code

ConfigureEndpointDefaults and ConfigureHttpsDefaults can be used to change default settings for ListenOptions and HttpsConnectionAdapterOptions, including overriding the default certificate specified in the prior scenario. ConfigureEndpointDefaults and ConfigureHttpsDefaults should be called before any endpoints are configured.

Server Name Indication (SNI) can be used to host multiple domains on the same IP address and port. For SNI to function, the client sends the host name for the secure session to the server during the TLS handshake so that the server can provide the correct certificate. The client uses the furnished certificate for encrypted communication with the server during the secure session that follows the TLS handshake.

Kestrel supports SNI via the ServerCertificateSelector callback. The callback is invoked once per connection to allow the app to inspect the host name and select the appropriate certificate.

SNI support requires:

Running on target framework netcoreapp2.1. On netcoreapp2.0 and net461, the callback is invoked but the name is always null. The name is also null if the client doesn't provide the host name parameter in the TLS handshake.

All websites run on the same Kestrel instance. Kestrel doesn't support sharing an IP address and port across multiple instances without a reverse proxy.

These methods are useful for making code work with servers other than Kestrel. However, be aware of these limitations:

SSL can't be used with these approaches unless a default certificate is provided in the HTTPS endpoint configuration (for example, using KestrelServerOptions configuration or a configuration file as shown earlier in this topic).

When both the Listen and UseUrls approaches are used simultaneously, the Listen endpoints override the UseUrls endpoints.

IIS endpoint configuration

When using IIS, the URL bindings for IIS override bindings are set by either Listen or UseUrls. For more information, see the ASP.NET Core Module topic.

When using IIS, the URL bindings for IIS override bindings set by UseUrls. For more information, see the ASP.NET Core Module topic.

Transport configuration

With the release of ASP.NET Core 2.1, Kestrel's default transport is no longer based on Libuv but instead based on managed sockets. This is a breaking change for ASP.NET Core 2.0 apps upgrading to 2.1 that call WebHostBuilderLibuvExtensions.UseLibuv and depend on either of the following packages:

Only HTTP URL prefixes are valid. Kestrel doesn't support SSL when configuring URL bindings using UseUrls.

IPv4 address with port number

http://65.55.39.10:80/

0.0.0.0 is a special case that binds to all IPv4 addresses.

IPv6 address with port number

http://[0:0:0:0:0:ffff:4137:270a]:80/

[::] is the IPv6 equivalent of IPv4 0.0.0.0.

Host name with port number

http://contoso.com:80/
http://*:80/

Host names, *, and +, aren't special. Anything not recognized as a valid IP address or localhost binds to all IPv4 and IPv6 IPs. To bind different host names to different ASP.NET Core apps on the same port, use HTTP.sys or a reverse proxy server, such as IIS, Nginx, or Apache.

Warning

If not using a reverse proxy with host filtering enabled, enable host filtering.

Host localhost name with port number or loopback IP with port number

http://localhost:5000/
http://127.0.0.1:5000/
http://[::1]:5000/

When localhost is specified, Kestrel attempts to bind to both IPv4 and IPv6 loopback interfaces. If the requested port is in use by another service on either loopback interface, Kestrel fails to start. If either loopback interface is unavailable for any other reason (most commonly because IPv6 isn't supported), Kestrel logs a warning.

Host names, *, and + aren't special. Anything that isn't a recognized IP address or localhost binds to all IPv4 and IPv6 IPs. To bind different host names to different ASP.NET Core apps on the same port, use WebListener or a reverse proxy server, such as IIS, Nginx, or Apache.

Host localhost name with port number or loopback IP with port number

http://localhost:5000/
http://127.0.0.1:5000/
http://[::1]:5000/

When localhost is specified, Kestrel attempts to bind to both IPv4 and IPv6 loopback interfaces. If the requested port is in use by another service on either loopback interface, Kestrel fails to start. If either loopback interface is unavailable for any other reason (most commonly because IPv6 isn't supported), Kestrel logs a warning.

Unix socket

http://unix:/run/dan-live.sock

Port 0

When the port number is 0 is specified, Kestrel dynamically binds to an available port. Binding to port 0 is allowed for any host name or IP except for localhost.

When the app is run, the console window output indicates the dynamic port where the app can be reached:

Now listening on: http://127.0.0.1:48508

URL prefixes for SSL

If calling the UseHttps extension method, be sure to include URL prefixes with https::

On macOS, Linux, and Windows, certificates can be created using OpenSSL.

Host filtering

While Kestrel supports configuration based on prefixes such as http://example.com:5000, Kestrel largely ignores the host name. Host localhost is a special case used for binding to loopback addresses. Any host other than an explicit IP address binds to all public IP addresses. None of this information is used to validate request Host headers.

As a workaround, host behind a reverse proxy with host header filtering. This is the only supported scenario for Kestrel in ASP.NET Core 1.x.

As a workaround, use middleware to filter requests by the Host header:

Host Filtering Middleware is disabled by default. To enable the middleware, define an AllowedHosts key in appsettings.json/appsettings.<EnvironmentName>.json. The value is a semicolon-delimited list of host names without port numbers:

appsettings.json:

{
"AllowedHosts": "example.com;localhost"
}

Note

Forwarded Headers Middleware also has an ForwardedHeadersOptions.AllowedHosts option. Forwarded Headers Middleware and Host Filtering Middleware have similar functionality for different scenarios. Setting AllowedHosts with Forwarded Headers Middleware is appropriate when the Host header isn't preserved while forwarding requests with a reverse proxy server or load balancer. Setting AllowedHosts with Host Filtering Middleware is appropriate when Kestrel is used as an edge server or when the Host header is directly forwarded.