Nginx wildcard proxy, pass subdomain to the server (upstream proxy)

sirkubax picture sirkubax · Oct 18, 2012 · Viewed 26.6k times · Source

I would like to be able to pass subdomain.domain.com to .domain.com apache server, with subdomain info too.

I would like to make a nginx cache for domain, acting like wildcard, but passing subdomain to the destination (there is apache witch wildcard too). Up to now, I pass the info via proxy_set_header Host $host; but I would like to have request with subdomain at the apache server.

  upstream domain.com {
    server 172.1.1.1:80 weight=50 fail_timeout=30s;
  }

  server {
    server_name *.domain.com;

    location / {
      proxy_pass http://domain.com;
      #proxy_pass $request;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;
     }

    location ~* ^.+.    (jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|swf)$ {
     proxy_pass http://topmanagergame.com;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_cache my-cache;
     proxy_cache_valid  200 302  30m;
     proxy_cache_valid  404      1m;
    }

    access_log /var/log/nginx/domain.com.log main;
    error_log off;
 }

Do you think I can use proxy_pass with upstream ?

Nginx (*wildcard_domain.com) --(cache)--> Apache (*wildcard_domain.com)
Nginx (anything.domain.com) --(cache)--> Apache (anything.domain.com)

Answer

dmytrivv picture dmytrivv · Dec 25, 2014
upstream somestring {
    server domain2.com:80 weight=50 fail_timeout=30s;
}

server {
    listen  80;
    server_name *.domain.com;

    server_name ~^(?<subdomain>.+)\.domain\.com$;

    location / {
        proxy_pass http://somestring;
        proxy_set_header   Host             $subdomain.domain2.com;
    }
}