Files
Protocolbot 7379d0c540 fix: rewrite asset and API paths for subdirectory deployments
index.html uses absolute /frontend/ paths for CSS and JS, and app.js
hardcoded const API = '/api'. In subdirectory deployments these resolve
to the wrong URL, causing unstyled HTML and broken API calls.

- index.php: rewrite /frontend/ references in index.html with detected basePath
- app.js: derive BASE_PATH from the script's own URL and prefix API calls
2026-07-06 13:36:08 -06:00

69 lines
2.0 KiB
PHP
Executable File

<?php
// Root router — serve frontend or API
// Works at web root or in a subdirectory (e.g. /protocol-droid/)
// Detect the base path (for subdirectory deployments)
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '/index.php';
$basePath = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
// If basePath is just / or . , clear it
if ($basePath === '/' || $basePath === '.') $basePath = '';
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// Strip base path from URI for routing
if ($basePath && strpos($uri, $basePath) === 0) {
$uri = substr($uri, strlen($basePath));
}
if (preg_match('#^/api(/|$)#', $uri)) {
require __DIR__ . '/api/index.php';
exit;
}
// Everything else: serve frontend files
// Normalize the path to prevent traversal
$uri = preg_replace('#/+#', '/', $uri);
$file = __DIR__ . '/frontend' . $uri;
// Resolve real path and verify it's within the frontend directory
$real_file = realpath($file);
$frontend_dir = realpath(__DIR__ . '/frontend');
// Helper: serve index.html with asset paths rewritten for subdirectory deployments
$serve_index = function() use ($basePath) {
$index = __DIR__ . '/frontend/index.html';
if (file_exists($index)) {
header('Content-Type: text/html');
$html = file_get_contents($index);
// Rewrite absolute /frontend/ paths to include the base path
if ($basePath) {
$html = str_replace('/frontend/', $basePath . '/frontend/', $html);
}
echo $html;
exit;
}
http_response_code(404);
echo 'Frontend not found';
exit;
};
if ($real_file === false || strpos($real_file, $frontend_dir) !== 0) {
$serve_index();
}
if (!is_file($real_file)) {
$serve_index();
}
$ext = pathinfo($real_file, PATHINFO_EXTENSION);
$types = [
'css' => 'text/css',
'js' => 'application/javascript',
'html' => 'text/html',
'svg' => 'image/svg+xml',
'png' => 'image/png',
'jpg' => 'image/jpeg',
'json' => 'application/json',
];
if (isset($types[$ext])) header('Content-Type: ' . $types[$ext]);
readfile($real_file);