There is no virtual host config in Kestrel like there is in IIS, so you can't do it without using IIS or something else in front of Kestrel. The best workaround is to bind another port like 12345 and create a reverse proxy for it.
For example, you can use Caddy server to act as a reverse proxy. In Ubuntu:
Install caddy server
The following script will install caddy. Caddy acts as a reverse proxy server which serves multiple website in the same port.
cat /etc/apt/sources.list.d/caddy-fury.list | grep -q caddy || echo "deb [trusted=yes] https://apt.fury.io/caddy/ /" | tee -a /etc/apt/sources.list.d/caddy-fury.list
apt update
apt install -y caddy
Add new proxy website
The following function adds a new reverse proxy config for caddy.
add_caddy_proxy()
{
domain_name="$1"
local_port="$2"
cat /etc/caddy/Caddyfile | grep -q "an easy way" && echo "" > /etc/caddy/Caddyfile
echo "
$domain_name {
reverse_proxy /* 127.0.0.1:$local_port
}" >> /etc/caddy/Caddyfile
systemctl restart caddy.service
}
Get a valid port
This function will find an empty internal port so your ASP.NET Core app can listen to.
get_port()
{
while true;
do
local PORT=$(shuf -i 40000-65000 -n 1)
ss -lpn | grep -q ":$PORT " || echo $PORT && break
done
}
Register ASP.NET Core web app
And this function helps you register an ASP.NET Core web app as a service and listening for a specific port.
register_service()
{
service_name="$1" # my.service
local_port="$2" # 12345
run_path="$3" # .
dll="$4" # MyProject.dll
echo "[Unit]
Description=$dll Service
After=network.target
Wants=network.target
[Service]
Type=simple
ExecStart=/usr/bin/dotnet $run_path/$dll.dll --urls=http://localhost:$local_port/
WorkingDirectory=$run_path
Restart=always
RestartSec=10
KillSignal=SIGINT
Environment=\"ASPNETCORE_ENVIRONMENT=Production\"
Environment=\"DOTNET_PRINT_TELEMETRY_MESSAGE=false\"
[Install]
WantedBy=multi-user.target" > /etc/systemd/system/$service_name.service
systemctl enable $service_name.service
systemctl start $service_name.service
}
Run your ASP.NET Core app
After executing the previous steps, you can add your ASP.NET Core app behind caddy.
server="www.yourhostname.com"
app_path=/opt/myapp
port=$(get_port)
dotnet publish -c Release -o $app_path ./app.csproj
register_service "myapp" $port $app_path "MyApp"
add_caddy_proxy $server $port
You can do that multiple times so multiple ASP.NET Core app just runs on the same server.
Reference:
https://github.com/EdiWang/Moonglade/blob/master/Deployment/install.sh