Trying to secure media folder

Hi, I’m trying to build an intranet with kirby. So I was trying to secure the whole frontend. This works already for the frontend routes. But I can’t seem to block the access to the media folder.

I was following this guide: https://getkirby.com/docs/cookbook/security/files-firewall, but even after trying the code below all files are still created in the media folder:

<?php

use Kirby\Cms\App as Kirby;

Kirby::plugin('cookbook/files-firewall', [
    'components'   => [
        'file::url' => function ($kirby, $file) {
            return $kirby->url() . '/' . $file->parent()->id() . '/' . $file->filename();
        },
        'file::version' => function ($kirby, $file, array $options = []) {
            // if the file is protected, return the original file
            return $file;
        }
    ],
]);

Am I doing something wrong or are there better ways to secure the media folder for not logged in users?

I think this only works if you return the image from the content folder:

		'file::url' => function ($kirby, $file) {
				return $kirby->url() . '/content/' . $file->parent()->diruri() . '/' . $file->filename();

		},

This works indeed. But I was wondering if there is another way to block the media folder, when not logged in? Without losing the the thumbnails and the different sizes of the images.

You could write a custom PHP route for /media/(:all) that serves the images. That means you will have to read the binary image data in PHP and construct a HTTP response with the correct HTTP headers for that image format.

It might be easy-ish to do with PHP functions like readfile, file_get_contents or maybe the lower-level fread. There’s probably different valid ways to do it. I don’t know if Kirby has some helpers for that, or if other PHP packages could be useful here.

Note that you will probably have to modify the server configuration so that all requests go through PHP, instead of serving media files directly. For Apache, that means probably commenting out the two lines that skip rewriting requests to index.php for existing files and directories:

And when using the PHP dev server with Kirby’s kirby/router.php script as an entrypoint, you probably need to duplicate that router.php script in your own code and remove the part that does a return false for existing files (instructing the PHP dev server to serve the file as-is):

Or maybe just change this line to point to index.php instead of kirby/router.php:

A possible worry here is that the Panel login page may require anonymous access to /assets/* and maybe to /media/panel/*. So maybe routing all requests through PHP and Kirby won’t work, and instead you might want to only route requests for /media/pages/* through Kirby. That requires slightly different Apache and/or PHP config changes, but should be doable.

Interesting approach thank you for your insights!

Note that it is not possible to overwrite the media route with your own custom route.