title: Nginx variable for subdomain?
body: <p>I need a Guru's advice.</p>
  
  <p>On Nginx's <code>conf</code> file, I would like to get the subdomain as a variable in order to redirect accesses as follow.</p>
  
  <ul>
  <li>ACCESS: <code>http://userX.example.com/?hoo=bar</code></li>
  <li>REDIRECT: <code>http://example.com/userX/?hoo=bar</code></li>
  </ul>
  
  <p>But I get</p>
  
  <ul>
  <li>REDIRECT: <code>http://example.com/userX.example.com/?hoo=bar</code></li>
  </ul>
  
  <p>My current <code>_http.conf</code> settings are like below. So obviously it works so.</p>
  
  <pre><code>## default HTTP
  server {
      listen       80;
      server_name  default_server;
      return       301 http://example.com/$host$request_uri;
  }
  </code></pre>
  
  <p>Are there any vaiables or ways to do like below?</p>
  
  <pre><code>## default HTTP
  server {
      listen       80;
      server_name  default_server;
      return       301 http://example.com/$subdomain$request_uri;
  }
  </code></pre>
  
  <p>I know if the subdomain part is limited it can be redirected, but I have to add them each time and I want it to keep as simple as possible.</p>
  
  <p>Is there any simple way to do so?</p>
  
  <p><strong>[ENV]</strong>: CentOS:7.3.1611, nginx: nginx/1.13.3, *.example.com is targetted to the same server in NS settings.</p>
  
  <hr>
  
  <h3>Conclusion (2017/12/13)</h3>
  
  <p>Use a regular expression:</p>
  
  <pre><code>server {
      listen       80;
      server_name  ~^(?&lt;subdomain&gt;.+)\.example\.com$;
      return       301 http://example.com/$subdomain$request_uri;
  }
  </code></pre>
  
  <p>Ref: <a href="https://stackoverflow.com/questions/45318758/nginx-variable-for-subdomain/45321927#45321927">Comment</a>, <a href="http://nginx.org/en/docs/http/server_names.html#regex_names" rel="noreferrer">Document</a></p>