Nginx Reverse Proxy Builder · .NET / ASP.NET Core

Nginx Reverse Proxy Config for ASP.NET Core Kestrel (Forwarded Headers & SignalR)

Generate an Nginx reverse proxy server block for .NET / ASP.NET Core with URL prefix rewrite previews, Certbot SSL redirects, WebSocket upgrade headers, and Docker DNS checks.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Domain, Routing & Upstream

2. TLS, WebSockets & Directives

# /etc/nginx/sites-available/api.dotnetapp.com.conf
# Generated by OpsCheck DevTools — Validate with: sudo nginx -t && sudo systemctl reload nginx

# Required in http {} context (or top of sites-available file) for clean WebSocket upgrades
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    listen [::]:80;
    server_name api.dotnetapp.com;

    # Redirect all plaintext HTTP traffic permanently to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name api.dotnetapp.com;

    # Let's Encrypt Certbot TLS Certificates
    ssl_certificate     /etc/letsencrypt/live/api.dotnetapp.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.dotnetapp.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    client_max_body_size 50M;

    # Gzip compression for JSON, JS, CSS, and SVG responses
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;

    # Baseline HTTP Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;

        # WebSocket & Upgrade support (requires map $http_upgrade $connection_upgrade)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_cache_bypass $http_upgrade;

        proxy_connect_timeout 15s;
        proxy_send_timeout 3600s;
        proxy_read_timeout 3600s;
    }
}
$sudo nginx -t && sudo systemctl reload nginx
URL Routing TransformationPrefix Preserved
GET https://api.dotnetapp.com/usershttp://127.0.0.1:5000/users

Root location '/' forwards '/users' unchanged to upstream http://127.0.0.1:5000/users.

Configuration Diagnostics

  • infoRoot Proxy Path (/) Preserves Full Request URI

    GET https://api.dotnetapp.com/users -> Upstream receives http://127.0.0.1:5000/users. Root location '/' forwards '/users' unchanged to upstream http://127.0.0.1:5000/users.

  • passWebSocket Upgrade & Extended Timeout (3600s) Enabled

    Configured HTTP/1.1 Upgrade, Connection $connection_upgrade map, and extended proxy_read_timeout for persistent real-time sockets.

  • infoSingle-Layer CORS Policy Reminder

    This configuration intentionally omits Access-Control-Allow-Origin headers so your upstream backend framework (Laravel, FastAPI, Express, ASP.NET Core) owns CORS cleanly without duplicate header rejections.

Runs locally in your browser. Domain names and upstream topology are never sent to a server.

Common Nginx Error Log Pattern (.NET / ASP.NET Core)

When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for .NET / ASP.NET Core, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:

/var/log/nginx/error.log

2026/11/22 20:01:29 [error] 7402#7402: *891 upstream sent too big header while reading response header from upstream, client: 198.51.100.31, server: api.dotnetapp.com, request: "GET /signin-oidc?code=... HTTP/2.0", upstream: "http://127.0.0.1:5000/signin-oidc", host: "api.dotnetapp.com"

Reverse Proxy Architecture & Header Forwarding for .NET / ASP.NET Core

Deploying ASP.NET Core 8 or 9 on Linux with Kestrel behind Nginx is the official Microsoft-recommended architecture for high-performance .NET web APIs, Blazor Server apps, and SignalR hubs. Kestrel listens on http://127.0.0.1:5000 while Nginx terminates TLS, protects against malformed HTTP traffic, enforces upload size limits, and proxies HTTP/1.1 WebSocket upgrades cleanly.

Two .NET-specific issues regularly surface right after putting Nginx in front of Kestrel. First, ASP.NET Core ignores X-Forwarded-For and X-Forwarded-Proto unless app.UseForwardedHeaders() is registered at the very top of Program.cs; causing OpenID Connect / OAuth callbacks (like Azure AD or Auth0) to generate http:// redirect_uri mismatches and breaking HSTS or HTTPS redirection.

Second, ASP.NET Core Identity, Entra ID, and OpenID Connect routinely emit large chunked authentication cookies (Set-Cookie headers exceeding 4 KB–8 KB). Nginx's default proxy_buffer_size is only 4 KB on x86_64 Linux, causing Nginx to crash OAuth sign-in callbacks with HTTP 502 Bad Gateway and log "upstream sent too big header while reading response header from upstream." Raising proxy_buffers and proxy_buffer_size in Nginx resolves this immediately.

If your .NET backend also hosts SignalR hubs or Blazor Server circuits, keeping proxy_http_version 1.1, Upgrade/Connection headers, proxy_cache_bypass $http_upgrade, and an extended proxy_read_timeout ensures long-lived WebSocket circuits remain connected without unexpected Blazor reconnection modals.

For enterprise ASP.NET Core 8 and 9 services hosted on Ubuntu, Debian, or Alpine Linux containers behind Nginx, testing authentication flows (OpenID Connect, JWT Bearer, and cookie sessions) through the live HTTPS proxy before launch prevents the classic 502 header-buffer crash and HTTPS redirect loop. Configure Kestrel limits cleanly in appsettings.Production.json, keep Nginx proxy_buffer_size at 128k or higher for large claims payloads, verify ForwardedHeaders middleware executes first in Program.cs, and audit systemd journalctl logs alongside /var/log/nginx/error.log to verify clean startup and zero dropped SignalR connections.

Step-by-Step Nginx & .NET / ASP.NET Core Deployment Guide

Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.

  1. 1Register UseForwardedHeaders() First in ASP.NET Core Program.cs

    Program.cs

    Call app.UseForwardedHeaders() BEFORE UseAuthentication(), UseHttpsRedirection(), and UseCors() so Kestrel sees the true HTTPS scheme and client IP forwarded by Nginx.

    Program.cscsharp
    using Microsoft.AspNetCore.HttpOverrides;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders =
            ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
        // Loopback (127.0.0.1) is trusted by default; clear KnownNetworks/Proxies only in isolated Docker networks
    });
    
    var app = builder.Build();
    
    app.UseForwardedHeaders();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();
    app.Run("http://127.0.0.1:5000");
  2. 2Increase Nginx Proxy Header Buffers for ASP.NET Core Identity / OIDC Cookies

    /etc/nginx/sites-available/api.dotnetapp.com.conf

    Add proxy_buffer_size and proxy_buffers inside your Nginx location block so large JWT claims and OIDC Set-Cookie headers never trigger 502 "upstream sent too big header" errors.

    /etc/nginx/sites-available/api.dotnetapp.com.confnginx
    proxy_buffer_size       128k;
    proxy_buffers           4 256k;
    proxy_busy_buffers_size 256k;
  3. 3Run Kestrel as a Managed systemd Service on Linux

    /etc/systemd/system/kestrel-api.service

    Configure ASPNETCORE_URLS to bind exclusively to loopback 127.0.0.1:5000 and let systemd restart the process automatically on failures.

    /etc/systemd/system/kestrel-api.serviceini
    [Unit]
    Description=ASP.NET Core Kestrel API
    
    [Service]
    WorkingDirectory=/var/www/dotnet-api
    ExecStart=/usr/bin/dotnet /var/www/dotnet-api/Api.dll
    Restart=always
    RestartSec=5
    User=www-data
    Environment=ASPNETCORE_ENVIRONMENT=Production
    Environment=ASPNETCORE_URLS=http://127.0.0.1:5000
    
    [Install]
    WantedBy=multi-user.target
  4. 4Validate Nginx Config and Verify SignalR / HTTPS Forwarded Scheme

    terminal

    Reload Nginx safely and confirm Kestrel receives HTTPS scheme headers without redirect loops.

    terminalbash
    sudo nginx -t && sudo systemctl reload nginx
    curl -I https://api.dotnetapp.com/health

Common .NET / ASP.NET Core Nginx Reverse Proxy Pitfalls

Review these three production failure modes before reloading Nginx on staging or live servers.

Pitfall 1

502 "upstream sent too big header" During OAuth / Entra ID Logins

ASP.NET Core splits large authentication tickets across multiple Set-Cookie headers. Nginx's default 4 KB proxy_buffer_size overflows and returns 502 Bad Gateway right on /signin-oidc unless you configure proxy_buffer_size 128k; and proxy_buffers 4 256k;.

Pitfall 2

Infinite Redirect Loop From app.UseHttpsRedirection() Without UseForwardedHeaders()

When Nginx terminates HTTPS and forwards HTTP to Kestrel port 5000, Kestrel's UseHttpsRedirection() sees an HTTP request and responds with 307 to https://, looping forever unless UseForwardedHeaders() runs first.

Pitfall 3

Docker Bridge Proxies Rejected by Default KnownProxies

ASP.NET Core only trusts X-Forwarded-* headers from 127.0.0.1 by default. If Nginx runs in a separate Docker container (e.g., 172.18.0.2), you must add the Docker bridge subnet to KnownNetworks (or clear KnownProxies inside an isolated private network).

Related Tools

Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:

Frequently Asked Questions

Does ASP.NET Core SignalR require special Nginx headers?
Yes. SignalR uses WebSockets (and Server-Sent Events fallback). You need proxy_http_version 1.1, Upgrade $http_upgrade, Connection $connection_upgrade, proxy_cache_bypass $http_upgrade, and a high proxy_read_timeout (such as 3600s) so hubs stay connected.
Why does Nginx return 413 Request Entity Too Large even after setting [RequestSizeLimit] in .NET?
Nginx inspects Content-Length before forwarding the body to Kestrel. Raise client_max_body_size in Nginx to match or slightly exceed Kestrel's MaxRequestBodySize.
Should I keep Kestrel listening on HTTPS behind Nginx?
On the same host (127.0.0.1:5000), terminating TLS at Nginx and proxying plain HTTP over loopback is standard, faster, and avoids managing duplicate internal certificates.
How do I prevent Nginx from stripping Blazor Server streaming updates?
Blazor Server relies on a persistent SignalR WebSocket circuit at /_blazor. With HTTP/1.1 Upgrade headers and proxy_buffering off on the SignalR endpoint, DOM diffs stream instantaneously.
Browse all 10 Nginx guides →