security – How to simulate a 404 to obfuscate the existence of files that should not be accessed publicly?

When it comes to dealing with spammers and other bad actors, I follow a simple philosophy, give them as few hints as possible. For example, if they were to send out a bot to scan sites for a specific plugin with known vulnerabilities, they would first run a simple cursory scan on many sites, looking for a 200 HTTP status code response.

Many developers use the following snippet to protect these bad actors from abusing the files:

if ( ! defined( 'ABSPATH' ) ) {
    die();
}

This is good, but does nothing to stop the bad actor from snooping. For example, let’s say the Classic Editor plugin had a vulnerability (it doesn’t), the bad actor would be sniffing out:

https://example.com/wp-content/plugins/classic-editor/classic-editor.php

Which by default, will return a 200 status code, revealing its existence on the website. The bad actor might not care whatsoever that the core PHP files die when accessed directly. Perhaps they’ve found a vulnerability elsewhere, and now that they have their list of sites where the vulnerable plugin is installed, they can drill down further with their malware attempt.

Adding just one line of code, we can easily harden this technique:

if ( ! defined( 'ABSPATH' ) ) {
    http_response_code( 404 );
    die();
}

It’s not perfect, but security is all about layers; it’s about all the small things adding up to just a little more protection. Sure, if someone is targeting you specifically, they’re probably going to find the weaknesses, one way or the other, but in terms of general anti-spam measures, this is going to thwart a decent percentage of bots.

But, what about smarter spammers/bots that won’t fall for the 404 response, because they can otherwise detect that the page is just a white page of death and didn’t return the theme’s 404 template?

If you attempt to go to:

https://example.com/wp-content/plugins/classic-editor/classic-editor-this-file-really-does-not-exist.php

It’ll trigger the theme’s 404 template.

How exactly is WordPress detecting the 404 response in order to display the 404 template, and is there a way to trigger that manually?