Setup SSL/TLS using certbot with NGINX
January 6, 2020
Install Certbot #
add-apt-repository ppa:certbot/certbot
apt-get update
apt-get install python-certbot-nginx
Obtain the SSL/TLS Certificate #
certbot --nginx -d xyz.com -d www.xyz.com
Obtain wildcard Certificate #
certbot certonly --manual -d '*.xyz.com'
Install NGINX #
apt-get install nginx -y
Set Up NGINX #
NGINX Config file #
/etc/nginx/nginx.conf
#
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
include /etc/nginx/conf.d/*.conf;
}
NGINX Domain config file #
/etc/nginx/conf.d/nginx.conf
#
Ex. 3
server {
listen 443 ssl;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# RSA certificate
ssl_certificate /etc/letsencrypt/live/xyz.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/xyz.com/privkey.pem; # managed by Certbot
# Redirect non-https traffic to https
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
server_name domain.xyz.com;
root /usr/share/nginx/html/;
# For basic authenticaiton
location / {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
Ex. 2
server {
listen 443 ssl;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# RSA certificate
ssl_certificate /etc/letsencrypt/live/xyz.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/xyz.com/privkey.pem; # managed by Certbot
# Redirect non-https traffic to https
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
keepalive_timeout 5;
client_max_body_size 10M;
server_name domain.xyz.com;
location / {
add_header X-Served-By "My Servlet";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_pass http://127.0.0.1:3000;
}
}
Reload NGINX #
sudo nginx -t && sudo nginx -s reload