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 ~^(.+)$;
    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_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        /usr/local/nginx/conf/fastcgi_params;

One Reply to “Rewriting subdomains to the Document Root in Nginx”

Leave a Reply

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