title: nginx server configuration: subdomain to folder
body: <p>I migrated from Apache 2 to nginx and I've got problems to handly my subdomain control.
  What I want: When x.domain.tld is requested, <strong>internally</strong> rewrite to domain.tld/x</p>
  
  <p>The problem I've got is that nginx always redirects the page by telling the browser to redirect to. But what I really want is to do this internally, like Apache 2 did.
  Also, if I only request x.domain.tld, nginx returns a 404. It only works when I do x.domain.tld/index.php</p>
  
  <p>Here's my config:</p>
  
  <pre><code>server {
          listen      80 default;
          server_name _ domain.tld www.domain.tld ~^(?&lt;sub&gt;.+)\.domain\.tld$;
  
          root /home/domain/docs/;
  
          if ($sub) {
                  rewrite (.*) /$sub;
          }
  
          # HIDDEN FILES AND FOLDERS
          rewrite ^(.*)\/\.(.*)$ @404 break;
  
          location = @404 {
                  return 404;
          }
  
          # PHP
          location ~ ^(.*)\.php$ {
                  if (!-f $request_filename) {
                          return 404;
                  }
  
                  include       /etc/nginx/fastcgi_params;
                  fastcgi_pass  unix:/etc/nginx/sockets/domain.socket;
          }
  }
  </code></pre>
  
  <p>Thanks!</p>