I have multiple subdomains, all pointing to one machine, and one IP address. On this machine, I want to have nginx acting as a reverse proxy, and depending on which subdomain was used to access the machine, I want it to reverse proxy to a different server. All the examples I've seen of using nginx as a reverse proxy use location, but as I understand that only works for the path, not for different subdomains. How can I achieve what I want?
Asked
Active
Viewed 9.6k times
37
markasoftware
- 489
-
2This might be a bit too broad. Can you post more about what you've tried already? – Will Feb 01 '16 at 05:47
2 Answers
66
Unless I completely misread your question: You simply set up server blocks for each sub-domain and the define the correct reverse proxy for the root of that subdomain i.e. something along the lines of:
server {
server_name subdomain1.example.com;
location / {
proxy_pass http://hostname1:port1;
}
}
server {
server_name subdomain2.example.com;
location / {
proxy_pass http://hostname2:port2;
}
}
HBruijn
- 80,330
- 24
- 138
- 209
-
-
-
Is it possible to access those addresses over https? I have an A-RECORD for subdomain.example.com. Do I need some more configuration to enable ssl access? – elano7 Oct 23 '22 at 14:31
-
Now if I hit the IP address for
example.com, the requests are sent to the first server. How can prevent that? – Sнаđошƒаӽ Feb 28 '24 at 07:39 -
@elano7 You need to add
listen 443 ssl;, along withssl_certificateandssl_certificate_keydirectives, pointing to the certificate and the private key respectively. – Sнаđошƒаӽ Feb 28 '24 at 07:40
4
Pretty much the same way.
location /foo {
rewrite ^/foo(.+)$ /$1 break;
proxy_pass http://foo;
}
location /bar {
rewrite ^/bar(.+)$ /$1 break;
proxy_pass http://bar;
}
-
How does this work for subdomains though? The location and regex seem to be specifically for a path. – DBrown Mar 02 '22 at 14:58
-
1
-