Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tool to create domain with cert (nginx + letsencrypt)
#!/bin/sh
# Tool to create domain with cert
# ./domain.sh test.example.com 1234
# where 1234 - upstream port
# Input params
DOMAIN=$1
UPSTREAM_PORT=$2
# Check if config already exist (no overwrite)
if [ -f /etc/nginx/servers/$DOMAIN ]; then
echo "Config /etc/nginx/servers/$DOMAIN already exist. Remove it for continue"
exit 1;
fi
echo "Create SSL nginx config for $DOMAIN with upstream 127.0.0.1:$UPSTREAM_PORT"
mkdir -p /var/www/$DOMAIN
# Initial domain for obtain certs
echo "Create HTTP config"
cat << EOF > /etc/nginx/servers/$DOMAIN
server {
listen 80;
server_name $DOMAIN;
location '/.well-known/acme-challenge' {
default_type "text/plain";
allow all;
root /var/www/$DOMAIN/;
}
}
EOF
echo "Reload nginx"
nginx -s reload
letsencrypt -t -n --agree-tos --webroot -m email@example.com \
--webroot-path /var/www/$DOMAIN -d $DOMAIN \
certonly
# Update config with keys
echo "Create HTTPS config"
cat << EOF > /etc/nginx/servers/$DOMAIN
upstream localhost_$UPSTREAM_PORT {
server localhost:$UPSTREAM_PORT fail_timeout=0;
}
server {
listen 443 ssl;
server_name $DOMAIN;
access_log /var/log/nginx/${DOMAIN}_access.log;
error_log /var/log/nginx/${DOMAIN}_error.log warn;
ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
#include snippets/ssl-params.conf;
location / {
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header Host \$http_host;
proxy_redirect off;
proxy_buffers 8 16k;
proxy_buffer_size 32k;
proxy_pass http://localhost_$UPSTREAM_PORT;
}
}
# Letsencrypt webroot
server {
listen 80;
server_name $DOMAIN;
location '/.well-known/acme-challenge' {
default_type "text/plain";
allow all;
root /var/www/$DOMAIN/;
}
location / {
return 301 https://\$host\$request_uri;
}
}
EOF
echo "Reload nginx"
nginx -s reload
echo DONE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment