Section 1 of 6
Kestrel and Reverse Proxies
🎯 What You'll Learn
- What is Kestrel
- Why use a reverse proxy
- Nginx configuration
- Apache configuration
- Kestrel configuration
What is Kestrel?
Kestrel is the cross-platform web server included with ASP.NET Core. It's fast, lightweight, and can run standalone or behind a reverse proxy.
Why Use a Reverse Proxy?
- SSL/TLS termination: Handle HTTPS certificates
- Load balancing: Distribute traffic across servers
- Static file serving: Serve static files efficiently
- Security: Additional security layer
- Caching: Cache responses
Nginx as Reverse Proxy
/etc/nginx/sites-available/inventtrack
Nginx
server {
listen 80;
server_name inventtrack.com www.inventtrack.com;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Enable Site
Bash
sudo ln -s /etc/nginx/sites-available/inventtrack /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
Apache as Reverse Proxy
/etc/apache2/sites-available/inventtrack.conf
Apache
<VirtualHost *:80>
ServerName inventtrack.com
ServerAlias www.inventtrack.com
ProxyPreserveHost On
ProxyPass / http://localhost:5000/
ProxyPassReverse / http://localhost:5000/
RequestHeader set X-Forwarded-Proto "http"
</VirtualHost>
Enable Modules and Site
Bash
sudo a2enmod proxy proxy_http headers
sudo a2ensite inventtrack
sudo systemctl reload apache2
Kestrel Configuration
appsettings.json
JSON
{
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5000"
},
"Https": {
"Url": "https://localhost:5001",
"Certificate": {
"Path": "/path/to/cert.pfx",
"Password": "password"
}
}
}
}
}
Configure in Program.cs
Program.cs
C#
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenLocalhost(5000);
options.ListenLocalhost(5001, listenOptions =>
{
listenOptions.UseHttps("/path/to/cert.pfx", "password");
});
});
Forwarded Headers
Configure your app to work behind a reverse proxy.
Program.cs
C#
using Microsoft.AspNetCore.HttpOverrides;
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
var app = builder.Build();
app.UseForwardedHeaders(); // Must be before UseAuthentication
Key Takeaways
- Kestrel: Cross-platform web server
- Reverse proxy: Nginx or Apache in front of Kestrel
- Benefits: SSL termination, load balancing, security
- Nginx: proxy_pass to Kestrel
- Apache: ProxyPass to Kestrel
- Forwarded headers: UseForwardedHeaders() middleware