Nginx domain setup script

After writing a number of scripts to auto create domains for Apache and Nginx on linux servers I’ve finally gotten round to cleaning it up and releasing by current script to handle auto creating domains for Nginx (my current preferred web server)

This creates the Nginx virtual host config file, sets up a sane folder structure for the domain, enables the domain in Nginx and reloads Nginx.

Hope this help other Nginx users to manage domains easier - let me know if you have any additions to the script

Note: script assumes using PHP via fastcgi and unix sockets.

Nginx auto domain setup script


# Info
# ---
# script can run with the domain as a command line input 
# `sudo ./` or without and
# the script will prompt the user for input


if [ -z "$1" ]

        #user input
        echo -e "Enter domain name:"
        read DOMAIN
        echo "Creating Nginx domain settings for: $DOMAIN"

        if [ -z "$DOMAIN" ]
                echo "Domain required"
                exit 1

if [ -z "$DOMAIN" ]

cat <<EOF
server {
        listen   80; ## listen for ipv4; this line is default and implied
        #listen   [::]:80 default_server ipv6only=on; ## listen for ipv6

        root $web_root/$DOMAIN/public;
        index index.php  index.html index.htm;

        # Make site accessible from http://localhost/
        server_name $DOMAIN www.$DOMAIN;

        location / {try_files $uri $uri/ @forum;}

        location ~ \.php$ {
                try_files $uri =404;

                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        location ~ /\.ht {
                deny all;
            access_log $web_root/$DOMAIN/log/access_log.txt;
            error_log $web_root/$DOMAIN/log/error_log.txt error;
) >  $config_dir/sites-available/$DOMAIN.conf

echo "Making web directories"
mkdir -p $web_root/"$DOMAIN"
mkdir -p $web_root/"$DOMAIN"/{public,private,log,backup} 
ln -s $config_dir/sites-available/"$DOMAIN".conf $config_dir/sites-enabled/"$DOMAIN".conf
/etc/init.d/nginx reload
echo "Nginx - reload"
chown -R www-data:www-data $web_root/"$DOMAIN"
chmod 755 $web_root/"$DOMAIN"/public
echo "Permissions have been set"
echo "$DOMAIN has been setup"

Justin Kelly

Justin Kelly

Data Engineeer, Business Analytics, Web Developer, Library Technology specialising in PHP and Tableau

Based in Melbourne, Australia

Feel free to contact me or _justin_kelly