Sending custom status headers

We would like to send a custom status header from a controller. Using Header::gone(); doesn’t seem to have any effect on the frontend.

What’s the correct way of specifying custom headers?

redirect to error page with status code of 410?

For unlisted pages, we’d like to display the page but send the status code 410.

have you tried sending header::gone in before:route hook? maybe controller is too late.

No, I haven’t yet, but I will take a look into this.

I just remembered a change during the latest K3 betas. Bastian posted on Slack:

In order to fix this once and for all I’ve come up with a way to configure the response in your controllers or templates and cache that configuration with the page. This new implementation has a lot of nice side effects.

Here’s how it looks like in a controller for example if you want to change the content type, the response code and set some headers.

$kirby
    ->response()
    ->code(202)
    ->type('rss')
    ->header('x-foo', 'bar');

My example doesn’t make that much sense, but I guess you see the potential. This is especially cool if you want to set custom error status codes on error pages, create a feed, json response or whatever else you have in mind.

Using this notation works like a charm.

4 Likes

can you post the snippet you ended using in your controller as well? just for the sake of documentation.

Yes, sure. This is in a controller:

<?php

return function($kirby, $page) {
    if ($page->isUnlisted()) {
        $kirby->response()->code(410);
    }

    // other logic here
};
1 Like