title: Redirecting a subdomain with a regular expression in nginx
body: <p>The nginx documentation says that the <a href="http://nginx.org/en/docs/http/server_names.html" rel="noreferrer">server_name directive</a> supports regular expressions. I've been banging my head against the wall trying to get even a trivial regex working.</p>
  
  <p>I want <a href="http://subdomain.mydomain.com" rel="noreferrer">http://subdomain.mydomain.com</a> to redirect to <a href="http://mydomain.com/subdomain" rel="noreferrer">http://mydomain.com/subdomain</a></p>
  
  <p>Here is my code.</p>
  
  <pre><code>server {
    server_name "~^subdomain\.mydomain\.com$";
    rewrite ^ http://mydomain.com/subdomain;
  }
  </code></pre>
  
  <p>Also, potentially noteworthy. Further down in the nginx config file there is a rule:</p>
  
  <pre><code>server {
    server_name *.mydomain.com
    ...
  }
  </code></pre>
  
  <p>What am I doing wrong?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>It has been suggested that I not use regex for this... to offer a little more clarity: the trivial regex was simply for purposes of troubleshooting.  The real regex will look more like...</p>
  
  <pre><code>server {
    server_name "~^.*(cvg|cincinnati)\.fakeairport(app)?\.(org|com)$";
    rewrite ^ http://fakeairport.com/cincinnati;
  }
  
  server {
    server_name "~^.*(lex|lexington)\.fakeairport(app)?\.(org|com)$";
    rewrite ^ http://fakeairport.com/lexington;
  }
  </code></pre>
  
  <p>So it would be preferable to use regex.</p>