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

    client_max_body_size 50M;
    charset utf-8;

    proxy_http_version 1.1;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    etag off;
    root {{ penpot_root_dir }}/frontend;

    location ~* \.(js|css).*$ {
        add_header Cache-Control "max-age=86400" always; # 24 hours
    }

    location ~* \.(html).*$ {
        add_header Cache-Control "no-cache, max-age=0" always;
    }

    location /api/export {
        proxy_pass http://localhost:{{ penpot_ports['exporter'] }};
    }

    location /api {
        proxy_pass http://localhost:{{ penpot_ports['backend'] }}/api;
    }

    location /dbg {
        proxy_pass http://localhost:{{ penpot_ports['backend'] }}/dbg;
    }

    location /ws/notifications {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_pass http://localhost:{{ penpot_ports['backend'] }}/ws/notifications;
    }

    location @handle_redirect {
        set $redirect_uri "$upstream_http_location";
        set $redirect_host "$upstream_http_x_host";
        set $redirect_cache_control "$upstream_http_cache_control";
        set $real_mtype "$upstream_http_x_mtype";

        proxy_buffering off;

        proxy_set_header Host "$redirect_host";
        proxy_hide_header etag;
        proxy_hide_header x-amz-id-2;
        proxy_hide_header x-amz-request-id;
        proxy_hide_header x-amz-meta-server-side-encryption;
        proxy_hide_header x-amz-server-side-encryption;
        proxy_pass $redirect_uri;

        add_header x-internal-redirect "$redirect_uri";
        add_header x-cache-control "$redirect_cache_control";
        add_header cache-control "$redirect_cache_control";
        add_header content-type "$real_mtype";
    }

    location /assets {
        proxy_pass http://localhost:{{ penpot_ports['backend'] }}/assets;
        recursive_error_pages on;
        proxy_intercept_errors on;
        error_page 301 302 307 = @handle_redirect;
    }

    location /internal/assets {
        internal;
        alias {{ penpot_root_dir }}/data/assets;
        add_header x-internal-redirect "$upstream_http_x_accel_redirect";
    }
}
