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;

Iptables Rules to allow Git

I have a client that wanted to use Git on their VPS. My firewall was blocking it and I had to do a little research. Git uses port 9418 to communicate. You don’t want to open up the port externally so I used stateful inspection to open the port only if we established the connection.

Here are the iptables rules:

# allow git
iptables -A OUTPUT -o eth0 -p tcp --dport 9418 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 9418 -m state --state ESTABLISHED -j ACCEPT