Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to setup Nginx config to auto redirect any domain/subdomain pointed(CNAME) to my static subdomain( to a respective directory inside /var/www. The directory will be named after the pointed domain/subdomain. I don't want to use VirtualHost or alter/restart Nginx everytime someone add new domain.

I stumble upon this answer but I still don't quite understand. What should I set as root directory?

current config :

server {
    listen 80 default_server;
    root /var/www/;
    index index.html index.htm;
share|improve this question
possible duplicate of Dynamic nginx domain root path based on hostname? – Michael Hampton Dec 24 '12 at 2:37
up vote 1 down vote accepted
rewrite  ^(.*)$  /$host/$1;

Add the above mentioned rewrite rule. This works as following. will map to /var/www/

The caveat is if the domain/subdomain directory doesn't exist nginx will throw an error.

share|improve this answer
Thanks, it works! However doesn't default to, any solution for this? – Matt Norad Dec 24 '12 at 3:14
You can add the index directive – Sameer Dec 24 '12 at 15:44
Already did that as per my original post. It works well before I add the rewrite rule. Now it return 404 error page. – Matt Norad Dec 25 '12 at 5:57

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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