upstream backend {
  zone upstreams 64K;
  server 127.0.0.1:3000;
  keepalive 32;
}

map $http_upgrade $connection_upgrade {
  default upgrade;
  '' close;
}

server {
  listen 80;
  listen [::]:80;
  server_name chatwoot.domain.com www.chatwoot.domain.com;

  access_log /var/log/nginx/chatwoot_access_80.log;
  error_log /var/log/nginx/chatwoot_error_80.log;

  return 301 https://chatwoot.domain.com$request_uri;
}

server {
  listen 443 ssl http2 reuseport;
  listen [::]:443 ssl http2 reuseport;
  server_name chatwoot.domain.com www.chatwoot.domain.com;

  underscores_in_headers on;

  access_log /var/log/nginx/chatwoot_access_443.log;
  error_log /var/log/nginx/chatwoot_error_443.log;

  location / {
    proxy_pass http://backend;
    proxy_redirect off;

    proxy_pass_header Authorization;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Ssl on; # Optional
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    client_max_body_size 0;
    proxy_read_timeout 36000s;
  }

  ssl_certificate /etc/letsencrypt/live/chatwoot.domain.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/chatwoot.domain.com/privkey.pem; # managed by Certbot
  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
  ssl_prefer_server_ciphers off;
  ssl_dhparam /etc/ssl/dhparam;
  ssl_early_data on;
  ssl_buffer_size 4k;
  ssl_session_cache shared:SSL:10m;
  ssl_session_timeout 1d;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}
