load(); $host = $_SERVER['HTTP_HOST'] ?? ''; $method = $_SERVER['REQUEST_METHOD']; // Load container mapping from domain config $config = json_decode(file_get_contents(__DIR__ . '/api/config.json'), true); $container = $config[$host] ?? null; $lxd = new LxdService(); // === Helper URLs === $redirectBase = parseUrl("$host/app"); // === If container is missing or invalid === if (!$container || !$lxd->containerExists($container)) { redirect($redirectBase); } // === Check container status === $state = $lxd->getContainerState($container)['metadata']['status'] ?? 'Stopped'; if ($state !== 'Running') { redirect($redirectBase); } // === Get container IP === $nginx = $lxd->getContainerServiceStatus($container, 'nginx'); $mysql = $lxd->getContainerServiceStatus($container, 'mariadb'); if ($nginx !== 'active' || $mysql !== 'active') { redirect($redirectBase); } // === Proxy to container === proxy($container, "http://{$host}{$requestUri}"); exit; // === Functions === function redirect(string $to): void { header("Location: $to", true, 302); exit; } function proxy(string $name, string $targetUrl): void { Proxy::$ENABLE_AUTH = false; Proxy::$HEADER_HTTP_PROXY_AUTH = 'HTTP_PROXY_AUTH'; $_SERVER['HTTP_PROXY_TARGET_URL'] = $targetUrl; $responseCode = Proxy::run(); touch($_ENV['STATEDIR']."/".$name); } function getFullUrl(): string { $protocol = (!empty($_SERVER['HTTPS']) || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME']; return $protocol . $host . $_SERVER['REQUEST_URI']; } function parseUrl(string $url = ''): string { $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'http'; return "$scheme://$url"; } function writeLog(string $name, string $uri): void { $logDir = __DIR__ . '/api/public/last-access-logs'; if (!is_dir($logDir)) { mkdir($logDir, 0777, true); } $logLine = date("Y-m-d H:i:s") . " : " . $uri . "\n"; file_put_contents("$logDir/$name.txt", $logLine, FILE_APPEND); }