# Keep in sync with web_nginx.conf
server {
    listen 80 default;
    listen [::]:443 ssl http2 ipv6only=on;
    listen 443 ssl http2;
    server_name localhost;

    ssl_certificate /etc/letsencrypt/live/covers.openlibrary.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/covers.openlibrary.org/privkey.pem;

    # Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
    ssl_dhparam /olsystem/etc/nginx/dhparam-2048.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
    ssl_prefer_server_ciphers on;
}

# Docker's internal load balancing ends up with unbalanced connections eventually.
# This must be kept in sync with the `replicas` value in `compose.production.yaml`
# for the `covers` service.
upstream covers_backend {
  least_conn;
  server openlibrary-covers-1:7075;
  server openlibrary-covers-2:7075;
}

server {
      listen 80;
      listen 443;
      server_name  covers.openlibrary.org;

      root /openlibrary;

      keepalive_timeout 5;

      # Return 429 errors as JSON.
      error_page 429 = @429;
      location @429 {
        default_type application/json;
        return 429 '{"status": 429, "message": "Too Many Requests. Please email us at info@archive.org"}';
      }

      location / {
        proxy_pass http://covers_backend;
        proxy_set_header Host $http_host;

        # Gunicorn takes IP from this header
        proxy_set_header X-Forwarded-For $remote_addr;

        # Hack to make the app pick the right url scheme even when the
        # app server is http only.
        proxy_set_header X-Scheme $scheme;

        if ($http_user_agent ~ (Bytespider) ) {
           return 444;
        }

        if ($http_user_agent ~ (CloudFront) ) {
           return 444;
        }


        # Covers rate limit.
        limit_req zone=cover_limit burst=400 nodelay;
        limit_req_status 429;
      }

      location ^~ /.well-known/acme-challenge/ {
        default_type "text/plain";
        root /openlibrary/static;
      }

      location ~ ^(/images/.*|favicon.ico|robots.txt)$ {
        rewrite ^(.*)$ /static/$1 last;
      }

      location ~ ^/(y_key_[0-9a-f]+.html|google[0-9a-f]+.html|LiveSearchSiteAuth.xml)$ {
        root /olsystem/www;
      }

      location /static {
        autoindex on;
        expires 1h;
      }

      location /static/build {
        expires max;
      }

      location /static/sitemaps {
        root /sitemaps;
      }
}
