1

I'm trying to configure nginx in a way that will mean less fiddling later down the road.

I don't want to have to create a config file for each domain and sub domain, I want a single configuration file that can handle all (or two if sub domain needs seperation from the main domain).

For example, let's say these domains are in use:

  • example.com
    • /var/www/example/public
  • www.example.com
    • /var/www/example/public
  • test.example.com
    • /var/www/example/subdomains/test/public
  • abc.example.com
    • /var/www/example/subdomains/abc/public
  • myothersite.com
    • /var/www/myothersite/public

Ofcourse www and non-www should no co-exist - so one should redirect to the other. Let's imagine I'm not redirecting from one to the other in this case, they should both use the same directory.

The above bullet points illustrate the type of directory structure I'm trying to achieve, however all my attempts have failed so far.

server {
    listen      80 default_server;
    server_name ~^(www\.)?(?<domain>.+)$;

    # Location of each domain
    location / {
        root   /var/www/$domain/public;
        index index.php index.html index.htm;
    }

    # ... some other config stuffs
}

I then attempted to set up a sub domain configuration file, however this one always seem to take presidence (and it also meant I had to name my site folders like "example.com" or "example.co.uk").

When I went to an address like "test.example.com" it would show up in the error logs as trying to access /var/www/test.example.com/public.

Any ideas? It is much appreciated!

I'm on CentOS 6.4 and nginx 1.0.15.

3

Here's a solution. It's not very elegant, but it works.

server {
    listen 80;
    server_name ~^(?<domain>[^\.]+)\.(?<tld>[^\.]+)$;
    root /var/www/$domain/public;

    location / {
       index index.php index.html index.htm;
    }
}

server {
    listen 80;
    server_name ~^(?<subdomain>[^\.]*)\.?(?<domain>[^\.]+)\.(?<tld>[^\.]+)$;
    root /var/www/$domain/subdomains/$subdomain/public;

    location / {
        if ($subdomain = 'www') {
            root /var/www/$domain/public;
        }
        index index.php index.html index.htm;
    }
}

It only works for two and three level domains mind you. E.g., foo.com and test.foo.com, but not more.test.foo.com.

  • Hi chrskly - thanks for the post. Managed to figure it out myself a few hours ago but have had family round so haven't been able to post answer. Here it is however: pastebin.com/GFZmg5gX ... If you want, you can adjust your answer to include this infomration and I'll pick it as best answer :-) so others can benefit too – David Jun 9 '13 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.