server {
  listen 443 ssl http2;
  server_name {{ psono_public_url | urlsplit('hostname') }};

  include /etc/nginx/nsible_conf.d/acme.inc;

{% if psono_cert_path is defined and psono_key_path is defined %}
  ssl_certificate     {{ psono_cert_path }};
  ssl_certificate_key {{ psono_key_path }};
{% elif psono_letsencrypt_cert is defined and bitwarden_letsencrypt_cert == True %}
  ssl_certificate     /var/lib/dehydrated/certificates/certs/{{ psono_public_url | urlsplit('hostname') }}/fullchain.pem;
  ssl_certificate_key /var/lib/dehydrated/certificates/certs/{{ psono_public_url | urlsplit('hostname') }}/privkey.pem;
{% elif psono_letsencrypt_cert is string %}
  ssl_certificate     /var/lib/dehydrated/certificates/certs/{{ psono_letsencrypt_cert }}/fullchain.pem;
  ssl_certificate_key /var/lib/dehydrated/certificates/certs/{{ psono_letsencrypt_cert }}/privkey.pem;
{% endif %}

  root {{ psono_root_dir }}/client;

  if ($request_method !~ ^(GET|POST|HEAD|PUT|DELETE)$ ) {
    return 405;
  }

  location @proxy {
    proxy_pass http://localhost:{{ psono_server_port }};
  }

  location /portal {
    alias {{ psono_root_dir }}/admin;
  }

  location / {
    try_files $uri $uri/index.html @proxy;
  }

  add_header X-Frame-Options "DENY";
  add_header X-Content-Type-Options "nosniff";
  add_header X-XSS-Protection "1; mode=block";
  add_header Strict-Transport-Security "$hsts_header";

  # Send info about the original request to the backend
  proxy_set_header X-Forwarded-For "$proxy_add_x_forwarded_for";
  proxy_set_header X-Real-IP "$remote_addr";
  proxy_set_header X-Forwarded-Proto "$scheme";
  proxy_set_header X-Forwarded-Host "$host";
  proxy_set_header Host "$host";

  # Handle websocket proxying
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection $connection_upgrade;
  proxy_http_version 1.1;

  # Set the timeout to read responses from the backend
  proxy_read_timeout 60s;

  # Enable Keep Alive to the backend
  proxy_socket_keepalive on;

  # Disable buffering large files
  proxy_max_temp_file_size 5m;

  allow 127.0.0.1;
{% for ip in psono_web_src_ip %}
  allow {{ ip }};
{% endfor %}
  deny all;
}
