Created
September 24, 2020 21:34
-
-
Save 0xAliRaza/327ec99fff803417c5d06ba609255b49 to your computer and use it in GitHub Desktop.
A handy shell script to create Nginx server-block (virtual host).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Nginx - new server block | |
# Functions | |
ok() { echo -e '\e[32m'$1'\e[m'; } # Green | |
die() { | |
echo -e '\e[1;31m'$1'\e[m' | |
exit 1 | |
} | |
# Variables | |
NGINX_AVAILABLE_VHOSTS='/etc/nginx/sites-available' | |
NGINX_ENABLED_VHOSTS='/etc/nginx/sites-enabled' | |
WEB_DIR='/var/www' | |
WEB_USER='www-data' | |
USER='ali' | |
NGINX_SCHEME='$scheme' | |
NGINX_REQUEST_URI='$request_uri' | |
# Sanity check | |
[ $(id -g) != "0" ] && die "Script must be run as root." | |
[ $# != "1" ] && die "Usage: $(basename $0) domainName" | |
# Create nginx config file | |
cat >$NGINX_AVAILABLE_VHOSTS/$1 <<EOF | |
server { | |
listen 80; | |
listen [::]:80; | |
server_name $1; | |
root /var/www/$1/; | |
index index.html index.htm index.php index.nginx-debian.html; | |
location / { | |
# First attempt to serve request as file, then | |
# as directory, then fall back to displaying a 404. | |
try_files \$uri \$uri/ =404; | |
autoindex on; | |
} | |
location ~ \.php$ { | |
include snippets/fastcgi-php.conf; | |
# With php-fpm (or other unix sockets): | |
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; | |
# With php-cgi (or other tcp sockets): | |
#fastcgi_pass 127.0.0.1:9000; | |
} | |
} | |
EOF | |
echo -e "\n#Added by nginx-server-block-generator.sh\n127.0.0.1 $1" >> /etc/hosts | |
# Changing permissions | |
chown -R $USER:$USER $WEB_DIR/$1 | |
# Enable site by creating symbolic link | |
ln -s $NGINX_AVAILABLE_VHOSTS/$1 $NGINX_ENABLED_VHOSTS/$1 | |
# Restart | |
echo "Do you wish to restart nginx?" | |
select yn in "Yes" "No"; do | |
case $yn in | |
Yes) | |
/etc/init.d/nginx restart | |
break | |
;; | |
No) exit ;; | |
esac | |
done | |
ok "Site Created for $1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment