error_log "{{LOG_DIR}}/nginx_error.log";
pid "{{LOG_DIR}}/nginx.pid";
worker_processes 1;
events {
    worker_connections 1024;
}
http {
    include "{{CONF_DIR}}/mime.types";
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    server {
        listen {{LISTEN_ADDRESS}}:{{PORT}};
        server_name localhost;
        root "{{ROOT}}";
        index index.php index.html index.htm;

        location / {
            # Try global root first, fallback to @project_fallback if not found
            error_page 404 = @project_fallback;
            try_files $uri $uri/ =404;
        }

        # Handle root-relative asset requests from project folders
        location @project_fallback {
            # Skip for common non-project paths
            if ($uri ~* ^/(favicon\.ico|phpmyadmin|admin)) {
                return 404;
            }
            # Capture project slug from Referer header (e.g., http://localhost/my-project/...)
            if ($http_referer ~* "^https?://[^/]+/([^/]+)/") {
                set $proj_slug $1;
                rewrite ^(.*)$ /$proj_slug$1 last;
            }
            return 404;
        }

        {{PROJECTS}}

        location /phpmyadmin {
            alias "{{PHPMYADMIN_DIR}}";
            index index.php;
            location ~ ^/phpmyadmin/(.+\.php)$ {
                alias "{{PHPMYADMIN_DIR}}/$1";
                fastcgi_pass 127.0.0.1:{{PHP_PORT}};
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $request_filename;
                include "{{CONF_DIR}}/fastcgi_params";
            }
        }

        location ~ \.php$ {
            # Use $request_filename for consistent behavior across global and project configs
            include "{{CONF_DIR}}/fastcgi_params";
            fastcgi_pass 127.0.0.1:{{PHP_PORT}};
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $request_filename;
        }
    }
}
