nginx server configuration: subdomain to folder

quotient7 picture quotient7 · Feb 10, 2012 · Viewed 28.3k times · Source

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, internally rewrite to domain.tld/x

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

Here's my config:

server {
        listen      80 default;
        server_name _ domain.tld www.domain.tld ~^(?<sub>.+)\.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;
        }
}

Thanks!

Answer

Mira Weller picture Mira Weller · May 20, 2013

As I found this Q&A on Google while looking for a solution for the same problem, I wanted to post the solution I finally used.


The first server block by MTeck looks pretty nice, but for the subdomains part you could simply do the following:

server {
  listen 80;
  server_name "~^(?<sub>.+)\.domain\.tld$";

  root /path/to/document/root/$sub;

  location / { try_files $uri $uri/ /index.php; }

  location ~ \.php {
    include fastcgi_params;
    fastcgi_pass  unix:/etc/nginx/sockets/domain.socket;
  }
}

This makes the root configuration directive dependent on the subdomain.