header routing

This commit is contained in:
bronku 2025-11-25 11:45:06 +01:00
parent ef47d7082c
commit 71d1b559a8
5 changed files with 36 additions and 55 deletions

View file

@ -1,13 +1 @@
hello from nginx!
<button onclick="goToApp('java')">Go to Java</button>
<button onclick="goToApp('dotnet')">Go to .NET</button>
<script>
function goToApp(appName) {
fetch("/", {
headers: { "X-App-Type": appName },
})
.then((r) => r.text())
.then((t) => (document.body.innerHTML = t));
}
</script>
welcome to nginx

View file

@ -1,52 +1,30 @@
events {}
events { }
http {
upstream dotnet_app {
server dotnet-1;
server dotnet-2;
}
upstream java_app {
server java-1;
server java-2;
}
# Map the header to the chosen upstream
map $http_x_app_type $app_upstream {
dotnet dotnet_app;
java java_app;
default "";
map $http_x_app_type $app_backend {
default dotnet_app;
"dotnet" dotnet_app;
"java" java_app;
}
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
#
# 1) If header is present -> route here
#
location @proxy_handler {
proxy_pass http://$app_upstream;
location / {
proxy_pass http://$app_backend;
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;
}
#
# 2) Default location for all requests
#
location / {
# If upstream selected -> jump to proxy handler
error_page 418 = @proxy_handler;
if ($app_upstream != "") {
return 418;
}
# Otherwise serve index.html or static files
try_files $uri $uri/ /index.html;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}