Rewriting subdomains to the Document Root in Nginx

I spent a little bit of time on this today getting my development environment working this morning on my new laptop. I wanted to be able to create a new folder inside a directory and not have to create a Nginx config each time.

This is just a minimal conf and you can add in all the whistles and bells that you like. The part that had me stuck was setting the variable. The searches I originally did showed the config working without having to set a variable, just using $1 from the regex in the root value. Once I set the variable and replaced the variable in the root directive it all fell into place.

Hope this helps someone :)

server {

    server_name ~^(.+)\.example\.com$;

    set $file_path $1;

    root    /home/$file_path/public_html;
    index   index.html index.php;

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

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        /usr/local/nginx/conf/fastcgi_params;
    }

}
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>