coldmind
coldmind

Reputation: 5417

Rewrite wildcard subdomain to the concrete top-level domain

How can I configure nginx to rewrite <somesubdomain>.mydomain.com to mydomain.com/some/url/path/<somesubdomain>/?

somesubdomain is a wildcard subdomain.

The main requirement is NOT REDIRECT, <somesubdomain>.mydomain.com should be a mask for mydomain.com/some/url/path/<somesubdomain>/.

Also, accessing other urls different from / (like somesubdomain.mydomain.com/test/) should not show anything.

Please note that I have a proxy for / configured for mydomain.com, so /some/url/path/<somesubdomain>/ should be passed and resolved by server which is proxied:

    location / {
        proxy_pass         http://app_servers;
        proxy_redirect     off;
        proxy_set_header   Host $http_host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        proxy_connect_timeout 10;
        proxy_read_timeout 10;
    }

Upvotes: 0

Views: 611

Answers (2)

Dmitry MiksIr
Dmitry MiksIr

Reputation: 4445

server {
   # server name with regexp
   server_name ~^(?<sub>[^.]+)\.mydomain\.com$;
   # now this server will catch all requests to xxxx.mydomain.com
   # and put "xxxx" to $sub variable

   # location _only_ for "/" URI
   # we can do it using "=" sign (means "exactly")
   location = / {
        # finally we want to request different URI from remote server
        proxy_pass http://app_servers/some/url/path/$sub/;
        # proxy_redirect will rewrite Location: header from backend
        # or you can leave proxy_redirect off;
        proxy_redirect http://app_servers/some/url/path/$sub/ http://$sub.mydomain.com/;
        ....
   }
   # next location for all other requests
   location / {
      return 404;
   }
}

Upvotes: 1

coldmind
coldmind

Reputation: 5417

It works with this configuration (added by current server{} section):

if ($host ~* (?<subdomain>[a-z0-9]+)\.mydomain\.com) {
    rewrite ^/$ /some/path/$store_subdomain break;
}

Upvotes: 0

Related Questions