Is there a way to use the Nginx stream
block for multiple types of traffic going to the same upstream server?
This works
http {
map $http_host $upstream {
example.com 1100;
www.example.com 1100;
}
upstream 1100 {
server 127.0.0.1:1100;
}
server {
listen 80;
location / {
proxy_pass http://$upstream;
proxy_set_header Host $host:80;
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;
}
}
}
stream {
map $ssl_preread_server_name $upstream {
example.com 1101;
www.example.com 1101;
}
upstream 1101 {
server 127.0.0.1:1101;
}
server {
listen 443;
proxy_pass $upstream;
ssl_preread on;
}
}
The Goal
Use the reverse proxy function to stream traffic to a background service. I do NOT want the traffic decrypted as it transits the reverse proxy. The certificates for the service reside on the upstream server; not the reverse proxy.
I will not list all the articles I have read trying to figure this out, but something along this line is what I am aiming for...
This is NOT a valid code block.
stream {
## ssl_preread_server_name does not work for for non-ssl traffic
map $ssl_preread_server_name $upstream {
example.com
## If unencrypted HTTP on port 80, route to upstream 1100
if ( unecrypted on port 80 ) { 1100;}
## If encrypted HTTPS on port 443, route to upstream 1101
if ( encrypted on port 443 ) { 1101;}
## If encrypted SSH on port 22, route to upstream 1102
if ( encrypted on port 22 ) { 1102;}
somethingelse.com
## If unencrypted HTTP on port 80, route to upstream 1200
if ( unecrypted on port 80 ) { 1200;}
## If encrypted HTTPS on port 443, route to upstream 1201
if ( encrypted on port 443 ) { 1201;}
## If encrypted SSH on port 22, route to upstream 1202
if ( encrypted on port 22 ) { 1202;}
}
upstream 1100 {
server 127.0.0.1:1100;
}
upstream 1101 {
server 127.0.0.1:1101;
}
upstream 1102 {
server 127.0.0.1:1102;
}
upstream 1200 {
server 127.0.0.1:1200;
}
upstream 1201 {
server 127.0.0.1:1201;
}
upstream 1202 {
server 127.0.0.1:1202;
}
server {
listen 80;
## Should route to 1100 or 1200 depending on domain
proxy_pass $upstream;
}
server {
listen 443;
## Should route to 1101 or 1201 depending on domain
proxy_pass $upstream;
ssl_preread on;
}
server {
listen 22;
## Should route to 1102 or 1202 depending on domain
proxy_pass $upstream;
}
}
There are two problems with that...
- It obviously does not work.
- If is evil - I really want to stay away from
if
If there is a better way to tackle this problem, I am open to it.