Skip to content

Instantly share code, notes, and snippets.

@pbredenberg
Last active August 8, 2018 02:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbredenberg/9024fa2f3df2eccda3c5 to your computer and use it in GitHub Desktop.
Save pbredenberg/9024fa2f3df2eccda3c5 to your computer and use it in GitHub Desktop.
Shell script to create nginx server blocks for wordpress website.
#!/usr/bin/env bash
#
# Nginx - new server block
# Based on this post: http://clubmate.fi/how-to-make-an-nginx-server-block-manually-or-with-a-shell-script/
# 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='distiller'
NGINX_SCHEME='$scheme'
NGINX_REQUEST_URI='$request_uri'
URI='$uri'
ARGS='$args'
DOCUMENT_ROOT='$document_root'
FASTCGI_SCRIPT_NAME='$fastcgi_script_name'
# 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;
root /var/www/$1/htdocs;
index index.php index.html index.htm;
server_name $1 www.$1;
location / {
try_files $URI $URI/ /index.php?q=$URI&$ARGS;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ \.php$ {
try_files $URI =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $DOCUMENT_ROOT$FASTCGI_SCRIPT_NAME;
include fastcgi_params;
}
# Logs
access_log $WEB_DIR/$1/logs/access.log;
error_log $WEB_DIR/$1/logs/error.log;
}
EOF
# Creating {public,log} directories
mkdir -p $WEB_DIR/$1/{htdocs,logs}
touch $WEB_DIR/$1/logs/access.log
touch $WEB_DIR/$1/logs/error.log
# Creating index.html file
cat > $WEB_DIR/$1/htdocs/index.html <<EOF
<!DOCTYPE html>
<html lang="en">
<head>
<title>$1</title>
<meta charset="utf-8" />
</head>
<body class="container">
<header><h1>$1<h1></header>
<div id="wrapper">
Hello World
</div>
<footer>© $(date +%Y)</footer>
</body>
</html>
EOF
# Changing permissions
chown -R $USER:$WEB_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