0

I have 2 different dns records. One for domain.com that points at a public ip address (i.e. 93.184.216.34) and one for local.domain.com that points at the local ip address (i.e. 10.0.0.2) for computers on the same network to use.

I have the following configuration to proxy_pass the local subdomain to the naked domain which seems to work:

server {
    listen 80;
    listen [::]:443 ssl;
    listen 443 ssl;
    
    # ssl config here

    server_name local.domain.com;

    location / {
        proxy_pass $scheme://127.0.0.1/;
        set $non_local_host domain.com;
        proxy_set_header Host $non_local_host;
        proxy_redirect http://$non_local_host/ http://$host/;
        proxy_redirect https://$non_local_host/ https://$host/;
    }
}

But I also need subdomains to work. foo.local.domain.com should proxy to foo.domain.com, and bar.baz.local.domain.com should proxy to bar.baz.domain.com

I understand that I need to duplicate the above server block. Change server_name to *.local.domain.com, but not sure how to properly set $not_local_host to point at the right subdomain.

The closest similar questions are: nginx sub-subdomain wildcard, but that was in the opposite direction (and never answered), and this answer to How can i pass subdomain as proxy_pass value in nginx?, but its for different domains (rather than subdomains) and it's some magic regex I don't understand. Thanks.

jgawrych
  • 3,322
  • 1
  • 28
  • 38

1 Answers1

1

You can try this one:

map $host $non_local_host {
    ~^(.*\.)?local\.domain\.com    "${1}domain.com";
}

server {
    listen 80;
    listen [::]:443 ssl;
    listen 443 ssl;
    
    # ssl config here

    server_name .local.domain.com;

    location / {
        proxy_pass $scheme://127.0.0.1/;
        proxy_set_header Host $non_local_host;
        proxy_redirect http://$non_local_host/ http://$host/;
        proxy_redirect https://$non_local_host/ https://$host/;
    }
}

The .local.domain.com server name will match local.domain.com and any of it's subdomains.

If your site make use of cookies, you may also need a proxy_cookie_domain directive:

proxy_cookie_domain $non_local_host $host;
Ivan Shatsky
  • 13,267
  • 2
  • 21
  • 37