Skip to content

Instantly share code, notes, and snippets.

@therokh
Last active March 11, 2018 09:46
Show Gist options
  • Save therokh/625e7cd0b3c160244ebdad82b0ea7434 to your computer and use it in GitHub Desktop.
Save therokh/625e7cd0b3c160244ebdad82b0ea7434 to your computer and use it in GitHub Desktop.
Script to create a new config file for Nginx reverse proxy, and obtain a certificate via LetsEncrypt certbot
#!/bin/bash
## This script creates a new Nginx proxy configuration based on two inputs:
## 1. Server hostname for incoming requests
## 2. Proxy destination IP to redirect to
HOSTNAME=$1
PROXYDEST=$2
## Colours
RED='\e[0;31m'
GREEN='\e[0;32m'
NOCOLOUR='\e[0m'
OKMESSAGE="${GREEN}OK${NOCOLOUR}"
FAILMESSAGE="${RED}FAIL${NOCOLOUR}"
# ===============================
## Grab a template nginx conf file and modify it for the new website
echo "===== Copying template ====="
cp /etc/nginx/conf.d/nginx_template.conf /etc/nginx/conf.d/${HOSTNAME}.conf
if [ $? -eq 0 ]; then
echo -e ${OKMESSAGE}
else
echo -e ${FAILMESSAGE}
exit 1
fi
echo "===== Replacing template data ====="
## Replace all the template hostname stuff with our real hostname
sed -i "s/template.placeholder.com/${HOSTNAME}/" /etc/nginx/conf.d/${HOSTNAME}.conf
sed -i "s/10.0.0.0/${PROXYDEST}/" /etc/nginx.conf.d/${HOSTNAME}.conf
if [ $? -eq 0 ]; then
echo -e ${OKMESSAGE}
else
echo -e ${FAILMESSAGE}
exit 1
fi
echo "===== Making directory for certbot ====="
## Make the directory for certbot
mkdir -p /var/www/${HOSTNAME}
chown nginx:nginx -R /var/www/${HOSTNAME}
if [ $? -eq 0 ]; then
echo -e ${OKMESSAGE}
else
echo -e ${FAILMESSAGE}
exit 1
fi
echo "===== Restarting nginx ====="
## Restart Nginx
systemctl restart nginx
if [ $? -eq 0 ]; then
echo -e ${OKMESSAGE}
else
echo -e ${FAILMESSAGE}
exit 1
fi
echo "===== Running certbot ====="
## Run certbot and generate a cert
certbot certonly --webroot -w /var/www/${HOSTNAME} -d ${HOSTNAME}
if [ $? -eq 0 ]; then
echo -e ${OKMESSAGE}
else
echo -e ${FAILMESSAGE}
exit 1
fi
echo "===== Replacing SSL cert in nginx config ====="
## Replace the config certificate with the new one
sed -i "s/www.placeholder.com/${HOSTNAME}/" /etc/nginx/conf.d/${HOSTNAME}.conf
if [ $? -eq 0 ]; then
echo -e ${OKMESSAGE}
else
echo -e ${FAILMESSAGE}
exit 1
fi
echo "===== Restart of Nginx to load new cert ====="
## Restart Nginx again
systemctl restart nginx
if [ $? -eq 0 ]; then
echo -e ${OKMESSAGE}
else
echo -e ${FAILMESSAGE}
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment