Skip to content

Instantly share code, notes, and snippets.

@kmvan
Last active May 26, 2021 10:14
Show Gist options
  • Save kmvan/cc6a3b34e7c4a97333ffe9c9ffe25200 to your computer and use it in GitHub Desktop.
Save kmvan/cc6a3b34e7c4a97333ffe9c9ffe25200 to your computer and use it in GitHub Desktop.
NextJS + certbot + nginx + nextjs+ SSL

/etc/nginx/snippets/ssl.conf

include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

/etc/letsencrypt/renewal/www.DOMAIN.conf

# renew_before_expiry = 30 days
version = 0.40.0
cert = /etc/letsencrypt/live/www.DOMAIN/cert.pem
privkey = /etc/letsencrypt/live/www.DOMAIN/privkey.pem
chain = /etc/letsencrypt/live/www.DOMAIN/chain.pem
fullchain = /etc/letsencrypt/live/www.DOMAIN/fullchain.pem
archive_dir = /etc/letsencrypt/archive/www.DOMAIN

# Options used in the renewal process
[renewalparams]
authenticator = nginx
installer = nginx
account = YOUR_ACCOUNT_HASH
server = https://acme-v02.api.letsencrypt.org/directory

/etc/nginx/sites-enabled/DOMAIN.conf

proxy_cache_path /tmp/DOMAIN levels=1:2 keys_zone=nextjs_static_DOMAIN:10m inactive=7d use_temp_path=off;
upstream nextjs_upstream_DOMAIN {
  server localhost:PORT;
}

server {
  listen 80;
  listen 443 ssl http2;
  server_name DOMAIN www.DOMAIN;
  access_log off;
  
  # SSLonfig
  ssl_certificate /etc/letsencrypt/live/DOMAIN/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/DOMAIN/privkey.pem;
  include snippets/ssl.conf;
  
  # proxy config
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection 'upgrade';
  proxy_set_header Host $host;
  proxy_cache_bypass $http_upgrade;
  
  # www redirect
  if ($host != DOMAIN) {
    return 301 https://DOMAIN$request_uri;
  }

  # SSL redirect
  if ($scheme = http) {
    return 301 https://$server_name$request_uri;
  }
  
  # static file
  location ~ .*\.(gif|jpg|jpeg|png|webp|bmp|swf|flv|mp4|ico|zip|7z)$ {
    root /home/www-data/DOMAIN/public;
    expires max;
  }
  # .well-known dir
  location /.well-known {
    root /home/www-data/DOMAIN/public;
  }
  
  location / {
    proxy_pass http://nextjs_upstream_DOMAIN;
  }
  
  # next assets dir
  location /_next/static {
    proxy_cache nextjs_static_DOMAIN;
    proxy_pass http://nextjs_upstream_DOMAIN;

    # For testing cache - remove before deploying to production
    add_header X-Cache-Status $upstream_cache_status;
    add_header Access-Control-Allow-Origin Origin;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment