Multiple Kestrel Vhosts

Host Multiple .Net sites

With the proof of concept up and running, how can we host a second domain or namevirtualhost on the same sever

It turns out that its simple enough to do, all you need is a second Kestrel service config:

sudo pico /etc/systemd/system/kestrel-virtualhost2.service

[Unit]
Description=virtualhost2 www.domain2.ext
[Service]
WorkingDirectory=/var/www/www.domain2.ext
ExecStart=/usr/bin/dotnet /var/www/www.domain2.ext/virtualhost2.dll
Restart=always
RestartSec=10
SyslogIdentifier=virtualhost2
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target

sudo systemctl enable kestrel-virtualhost2.service

(Once you have something to access you will need to start your Kestrel instance with:

sudo systemctl start kestrel-virtualhost2.service

)

So there's our second Kestrel service configured and ready to run.

Now for Apache you will need to add a virtual host conf file in /etc/apache2/sites-available/www.domain2.ext.conf

<VirtualHost *:80>
ServerAdmin serveradmin@domain2.ext
ServerName www.domain2.ext
ServerAlias domain2.ext
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:6000/
ProxyPassReverse / http://127.0.0.1:6000/
ErrorLog /var/log/apache2/domain2.ext-error.log
CustomLog /var/log/apache2/domain2.ext-access.log

The important change here is the Kestrel proxy port - obviously you can only have one instance of Kestrel listening on a port so if you used the default 5000 for your first virtualhost then you will need to change the port for the second.

Since you have changed Kestrel from the default port then you will need to tell your .Net project / solution / app that its running on a different port:

Simply add into your Program.cs the line

.UseUrls("http://127.0.0.1:6000")

So that your CreateWebHostBuilder looks like:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://127.0.0.1:6000")
.UseStartup();