To provide a dynamic file, you need to make a Controller with a method like:
public function serve(Request $request) {
$file_str = $file_system->realpath($module_handler->getModule('my_module')->getPath()) . '/assets/js/service-worker.js';
if (file_exists($file_str)) {
$response = new BinaryFileResponse($file_str, 200);
$response->headers->set('Content-Type', 'application/javascript');
// Allow same origin service worker.
$response->headers->set('Service-Worker-Allowed', '/');
return $response;
}
throw new NotFoundHttpException();
}
And then define a route for it, where the path is not existing as a static file, like:
example.serviceworker:
path: '/serviceworker'
defaults:
_controller: '\Drupal\my_module\Controller\ExampleController::serve'
requirements:
_permission: 'access content'
see - https://www.drupal.org/docs/drupal-apis/routing-system/introductory-drupal-8-routes-and-controllers-example.
.htaccess
or whatever, so that Drupal doesn't have to be bootstrapped to serve the file..htaccess
wouldn't work. I need to create the service worker an/or related cache files dynamically, as they need to be updated as the contents of my Drupal site change.