This is simple (no support for the url rewrite - when you want to serve spa on some path other than site root) controller I've made for the serving of the spa folder from arbitrary folder.
This implementation brings the benefit of having the symfony profiler toolbar - to help with debugging/profiling the ajax/fetch requests.
However I would recommend another approach for production - create a separate deployment for the spa app.
<?php
namespace App\Controller;
use Symfony\Component\Filesystem\Path;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\MimeTypesInterface;
use Symfony\Component\Routing\Annotation\Route;
#[Route(
path: '/',
)]
class SpaController
{
public function __construct(
private readonly MimeTypesInterface $mimeTypes,
private readonly string $documentRootPath,
private readonly string $indexFile,
)
{
}
#[Route(
path: '/{urlPath}',
requirements: [
'urlPath' => '.*',
],
utf8: true,
)]
public function spaIndex(string $urlPath): Response
{
if ('' === $urlPath) {
$urlPath = $this->indexFile;
}
if ($this->indexFile !== $urlPath) {
$filePath = Path::canonicalize($this->documentRootPath . $urlPath);
if (
Path::isBasePath($this->documentRootPath, $filePath)
&& is_file($filePath)
) {
$fileResponse = new BinaryFileResponse($filePath);
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
// symfony guessMimeType returns the wrong mime [`text/plain`] type for `.js`
$mimeType = $this->mimeTypes->getMimeTypes($ext)[0] ?? null;
if ($mimeType) {
$fileResponse->headers->set('Content-Type', $mimeType);
}
return $fileResponse;
}
// fallback to serving the indexFile bellow
}
// for symfony to inject the debug toolbar one must use response with text contents
$indexFileContents = file_get_contents($this->documentRootPath . $this->indexFile);
$response = new Response($indexFileContents);
$response->headers->set('Content-Type', 'text/html');
return $response;
}
}
.htaccess
(from thesymfony/apache-pack
package) should already just serve static files as is - did you modify it in any way? – Journeyman