Kestrel reverse proxy using nginx

When you self-host your Asp.NET Core web application using Kestrel, it is recommended that you don’t expose it to the outside world, but use a reverse proxy instead.

If you followed the sample in cross-platform Asp.NET Core then you found out that your self-hosted application is only available from your local machine. To expose your application to the outside world, the recommended approach is to use a reverse proxy using Apache or nginx.

Let’s see how can we configure a reverse proxy for Kestrel using nginx.

Install nginx from the official repository:

  1. Add the repository to your package manager by adding the snippet below to /etc/yum.repos.d/nginx.repo

    [nginx]
    name=nginx repo
    baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
    gpgcheck=0
    enabled=1

  2. Run the installer: yum install nginx

Configure nginx to act as a reverse proxy:

Create and add the contents below to /etc/nginx/proxy.conf :

proxy_redirect          off;
proxy_set_header        Connection keep-alive;
proxy_set_header        Host            $host;
proxy_set_header        X-Real-IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size    10m;
client_body_buffer_size 128k;
proxy_buffers           32 4k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      90;
proxy_next_upstream     error timeout invalid_header http_500 http_502 http_503 http_504;

Create and add the contents below to /etc/nginx/conf.d/reverse.conf :

server {
        listen   80;
        server_name  YOUR_WEBSITE_DOMAIN;

        access_log  /var/log/nginx/reverse_access.log;
        error_log  /var/log/nginx/reverse_error.log;

        location / {
                proxy_pass      http://localhost:5000;
                include         /etc/nginx/proxy.conf;
        }
}

Open /etc/nginx/nginx.conf and add the snippet below, if it is not present:

include /etc/nginx/conf.d/*.conf;

Start nginx and set it to start automatically on reboot:

chkconfig nginx on
service nginx start

Now your self-hosted site is available from the outside world.

http://dotnetcore.nimeshjm.com/

dotnet-core-kestrel-nginx

Following the steps on this post, you will be able to self-host an Asp.NET Core application using Kestrel and reverse proxy using nginx.