Last active
August 25, 2021 20:59
-
-
Save cmanish049/344f4cd957e99e6e762e26a3a595608d to your computer and use it in GitHub Desktop.
Create Virtual Host Shell Script
This file contains hidden or 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 | |
read -p "Enter username : " username | |
read -p "Enter domain name : " domain | |
# Functions | |
ok() { echo -e '\e[32m'$domain'\e[m'; } # Green | |
die() { echo -e '\e[1;31m'$domain'\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=$username | |
# 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/$domain.test <<EOF | |
server { | |
listen 80; | |
listen [::]:80; | |
root /var/www/$domain/public; | |
# Add index.php to the list if you are using PHP | |
index index.php index.html index.htm index.nginx-debian.html; | |
server_name $domain.test; | |
location / { | |
try_files \$uri \$uri/ /index.php?\$query_string; | |
} | |
# pass PHP scripts to FastCGI server | |
# | |
location ~ \.php$ { | |
include snippets/fastcgi-php.conf; | |
# fastcgi_index index.php; | |
#fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name; | |
#include fastcgi_params; | |
fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; | |
#fastcgi_pass 127.0.0.1:8080; | |
#fastcgi_split_path_info ^(.+\.php)(/.+)$; | |
} | |
location ~ /\.(?!well-known).* { | |
deny all; | |
} | |
} | |
EOF | |
# Changing permissions | |
chown -R $WEB_USER: $WEB_DIR/$domain | |
sudo chmod -R 777 /var/www/$domain/storage/ | |
# Enable site by creating symbolic link | |
sudo ln -s $NGINX_AVAILABLE_VHOSTS/$domain.test $NGINX_ENABLED_VHOSTS/$domain.test | |
#sudo sed -i '1s/^/127.0.0.1 '$domain.test'\n/' /etc/hosts | |
_etcHostLine="127.0.0.1 $domain.test" | |
if grep -Eq "127.0.0.1[[:space:]]+$domain.test" /etc/hosts; then | |
echo "Entry ${_etcHostLine} already exists in host file" | |
else | |
echo "127.0.0.1 $domain.test" >> /etc/hosts || _die "Unable to write host to /etc/hosts" | |
fi | |
# Restart | |
echo "Do you wish to restart nginx? y/n" | |
read -p "" yn | |
if [ "$yn" == "y" ]; then | |
sudo service nginx restart; | |
fi | |
ok "Virtual Host Created for $domain.test" |
curl -0 https://gist.githubusercontent.com/cmanish049/344f4cd957e99e6e762e26a3a595608d/raw/a409364420919bbc9bf958220191424cf789041a/vhost-nginx.sh -o vhost-nginx.sh
chmod +x vhost-nginx.sh
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
run command
sudo bash vhost-nginx.sh