How to return a 410 HTTP code and render a page?

I find Kirby’s routing very confusing when you want to do simpler stuff. I want to send a 410 header and return a response as if a certain page was rendered. I tried this:

App::plugin('my/plugin', [
	'hooks' => [
		'route:after' => function ($route, $path, $method) {
			Header::gone();
			return site()->visit('home');
		}
	]
]);

The homepage is always rendered, regardless of the URL, which is expected. However, the status code is 200, instead of 410, even though I explicitly set it via Header::gone(). How to fix this?

You can return a Response instance with the rendered page in the body like so:

$content = page('home')->render();

return new Kirby\Cms\Response($content, null, 410);

The second argument is for the response type. Make sure to set it if the response is not text/html.

You can also use this:

App::plugin('my/plugin', [
	'hooks' => [
		'route:after' => function ($route, $path, $method) {
			kirby()->response()->code(410);
			return site()->visit('home');
		}
	]
]);

The reason why Header::gone() does not work is that the response code that it sets is overridden by the one that Kirby sets when the page gets rendered. This is why we have our global response object that allows to set different kinds of header data.

1 Like