Skip to content

Instantly share code, notes, and snippets.

@shabayekdes
Last active December 14, 2021 21:51
Show Gist options
  • Save shabayekdes/27864d970f82797d0cd2df4a81994ea4 to your computer and use it in GitHub Desktop.
Save shabayekdes/27864d970f82797d0cd2df4a81994ea4 to your computer and use it in GitHub Desktop.
Create nginx block domain
#!/bin/bash
# Check if arguments is empty domain
if [ $# -eq 0 ]
then
echo "No arguments supplied"
fi
domain=$1
php="7.4"
if [ -n "$2" ]
then
php=$2
fi
root="/var/www/$domain/html"
block="/etc/nginx/sites-available/$domain"
# PATH TO YOUR HOSTS FILE
ETC_HOSTS=/etc/hosts
# DEFAULT IP FOR HOSTNAME
IP="127.0.0.1"
HOSTS_LINE="$IP\t$domain"
# Create the Document Root directory
sudo mkdir -p $root
# Assign ownership to your regular user account
sudo chown -R $USER:$USER $root
# Create the Nginx server block file:
sudo tee $block > /dev/null <<EOF
server {
listen 80;
listen [::]:80;
root /var/www/$domain/html;
index index.html index.htm;
server_name $domain www.$domain;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# pass PHP scripts to FastCGI server
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# # With php-fpm (or other unix sockets):
# fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/var/run/php/php$php-fpm.sock;
# fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
# include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
EOF
# Link to make it available
sudo ln -s $block /etc/nginx/sites-enabled/
# Test configuration and reload if successful
sudo nginx -t && sudo service nginx reload
if [ -n "$(grep $domain /etc/hosts)" ]
then
echo "$domain already exists : $(grep $domain $ETC_HOSTS)"
else
echo "Adding $domain to your $ETC_HOSTS";
sudo -- sh -c -e "echo '$HOSTS_LINE' >> /etc/hosts";
if [ -n "$(grep $domain /etc/hosts)" ]
then
echo "$domain was added succesfully \n $(grep $domain /etc/hosts)";
else
echo "Failed to Add $domain, Try again!";
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment