WordPress Health Check Interface Optimization: Building a Live Detection Plugin Using 204 Response
This article was last updated 149 days ago. The information in it may have developed or changed. If it is invalid, please leave a message in the comment section.

1 Introduction

In my previous multi-active architecture deployment practice (see:Home Data Center Series WordPress Multi-Active Architecture (Simplified Version) Implementation Plan in Personal Blog), Cloudflare's health checks are one of the core mechanisms for determining node availability. The content of the health checks in my previous blog is as follows:

image.png

The check path used in the figure above is "/healthcheck", which is a WordPress page I created specifically for this purpose. The content is very simple, just outputting a piece of "OK" text, so that Cloudflare can periodically initiate HTTP requests to confirm whether the site is alive:

image.png

At the same time, I also set up strategies such as bypassing cache, firewall, and security challenges for this path in Cloudflare's rules to ensure that the response results can truly reflect the status of the origin server as much as possible.

This solution is functional and has indeed run stably for a period of time. However, during further analysis and optimization, I found that this approach actually has many problems.Hidden structural problems:

  • First, this path returns a 200 status code with body content.Although the response body is small, it is still essentially a complete WordPress loading process. The server still needs to go through steps such as route parsing, plugin loading, and template rendering, which is not lightweight enough.
  • Secondly, this is an artificially constructed page path, and WordPress itself has no built-in semantics.In the future, if the site structure changes or the route is rewritten, it is easy for the path to fail due to negligence, but Cloudflare will not immediately perceive this anomaly.
  • The most important thing is that this path returns a 200 status codeEven if a serious error occurs inside WordPress (such as a plugin triggering a PHP error), as long as no 5xx is explicitly thrown, Cloudflare's health check will still be judged as "successful", which may result in a "false positive" - it appears to be available, but is actually down.

In addition, since it is a WordPress page, this solution is inevitably subject to the WordPress runtime mechanism and plugin intervention, further increasing uncertainty:

  • The page is ultimately controlled by WordPress's front-end routingEven if your page has no body content, WordPress will still load all plugins, theme hooks, and routing logic, causing performance overhead to increase unnecessarily.
  • SEO plugins like Rank Math, which will automatically inject structured data (such as JSON-LD) into the page, even if your page has no body, you may <head> Some add a lot of schema data, which is not useful for health checks and increases the response size.
  • Even if you have cache bypass rules enabled, Cloudflare APO or some plugin caches may still "secretly cache" page responses., especially in edge scenarios where certain paths and parameters do not hit the rules, resulting in the inspection results not being able to truly reflect the status of the origin site.

In summary, although this "using pages to simulate health checks" solution is simple and intuitive, it cannot completely bypass the internal operating mechanism of WordPress and there are still many uncontrollable factors. Especially when it comes to complex deployment scenarios such as multi-active, high availability, and CDN acceleration,This type of solution is more likely to misjudge service status due to cache interference, plugin injection or routing failure, is not an ideal long-term solution.

2 Sources of inspiration

Originally, even if there are some minor flaws when using a custom page for health checks, it can still be used normally overall. With my lazy personality, I will not go out of my way to research new methods.

However, I later discovered that many software, such as ShadowSocket, used this URL when conducting usability tests on various nodes:http://www.gstatic.com/generate_204":

image.png

The same is true for merlin clash2:
image.png

This makes me a little interested, why are these software used?http://www.gstatic.com/generate_204"What about this link as a test link? What's so special about it that so many tools use it as a standard for "judging whether the network is unobstructed"?

So I looked up the background of this address and unexpectedly discovered that this link was not a temporary product of some unknown website, but a "contentless" detection interface designed by Google specifically for Android network status detection: its return is very "clean" - no redirection, no text, no cache triggering, and no hijacking by operators (at least in many areas). The response code is fixed at 204 No Content, with no unnecessary overhead. It simply means "you hit this address, which means you can connect to the Internet."

And the "Health Check" page I created myself/healthcheckIn comparison, this method is obviously lighter, faster, more standardized, and more difficult to be tampered with or contaminated by operators.

More importantly, it inspired me to have an idea: since Google can make such an almost "perfect" network detection endpoint, then I can simulate the response logic of generate_204 and deploy it on different nodes of my blog (not necessarily bound to a specific page) as a unified detection endpoint forCloudflare's health checkuse?

3. Build my blog generate_204: Implement ideas and concepts

Based on the analysis above, neither the built-in WordPress "Posts" nor "Pages" are suitable for implementing the generate_204 response logic on my blog. The main problem is that they are designed for human visitors, not network detection programs. In particular, they have inherent limitations in rewrite rules, URL matching, and response body manipulation.

So, what are some more suitable paths to choose?

I have roughly sorted out three possible implementation methods:

  1. Site-level processing:

This bypasses WordPress and directly processes the /generate_204 path at the web server level. This approach offers the greatest advantages of high performance and independence, but it also means breaking away from WordPress's unified management system. For blog environments that rely on plugin automation and unified configuration, this fragmented management approach is costly to maintain and lacks flexibility for future expansion.

  1. Theme-level logic injection:

I injected logic into the current theme's functions.php or other hooks to recognize and respond to /generate_204 requests. This approach is more adaptable and also leverages WordPress environment variables. However, I prefer minimalist theme maintenance and didn't want this functional logic to contaminate the theme, so I opted against it.

  1. REST API route registration (plug-in method):

Use a WordPress plugin to add a responsive pseudo-page path (such as /generate_204). The plugin will register a custom REST API route, listen for requests to that path, and directly return the customized response content when a request arrives. This approach not only conforms to WordPress's extensibility mechanism, but also maintains a clear code structure, a single responsibility, and eases management and maintenance. It is particularly suitable for implementing long-term stable operations such as health checks.

In the end, I chose the third option:Add a responsive pseudo page path as a plugin and implement the complete logic of /generate_204 in the plugin. The reason is simple: this method does not rely on additional configuration of the Web Server layer, nor does it pollute my theme code. It also maintains clear logic and independent functions, which is very consistent with the principles of my current blog architecture.

4 Implementation Details: REST API Route Registration (Plugin Method)

4.1 Overview

Since our goal is to provide a live response interface that returns a 204 No Content response, we can fully utilize WordPress's built-in REST API system to achieve this requirement. WordPress's REST API is a fully functional and highly extensible mechanism that allows us to easily register custom routes without requiring any additional plugins or modifying the core code.

In designing this interface, I tried to maintain the principles of cleanliness and stealth. First, it responds to simple GET requests, accepting no parameters and returning no body text. Its sole purpose is to remain active. Second, it requires no authentication and uses a difficult-to-guess path (such as /wp-json/healthmonitor/check) to avoid being detected by general scanners. This interface is essentially machine-readable and shouldn't expose too much information, let alone its backend structure.

Interestingly, the 204 status code is often used for "processing successfully, but no content is returned." Compared to 200 OK, it has less HTTP message redundancy and allows various automated systems to complete the inspection process more quickly. From an "efficiency" perspective, it is a very suitable choice.

4.2 Advantages of the plug-in approach

Implementing this custom detection interface in the form of a plug-in has several significant advantages over directly modifying the theme code or relying on Web Server rewriting rules:

  • It has good structural independence, and all logic is encapsulated in the plug-in, which neither pollutes the theme directory nor causes confusion by stuffing the code into functions.php. This is especially important for subsequent maintenance and collaborative development.
  • This method is simpler and more direct in deployment. There is no need to adjust the rewrite rules of Nginx or Apache, nor to set up additional server path mapping. As long as the plug-in is enabled, the interface will naturally take effect, and it can maintain consistent performance even when deployed in various hosts or panel environments.
  • The portability of plugins is also a major advantage. If the blog needs to change servers, domain names, or even the entire architecture in the future, as long as the plugin files are still there, the activation interface can continue to be used without additional configuration. This "portability" feature is very consistent with the portability needs of modern blogs.
  • The plugin approach also demonstrates its security advantages. By explicitly declaring this route as requiring no authentication, the permission_callback function ensures that the interface remains accessible to the public. This avoids the default WordPress REST API restriction of only being accessible to logged-in users and prevents potential misjudgment of permissions. While maintaining an open interface, it also maximizes control over the boundaries of access rights.

4.3 Plugin Code Implementation

In order to implement a live detection interface dedicated to health checks, we can customize an extremely simple WordPress plug-in.

First, create a subdirectory in the WordPress plugins directory, for example named:

/wp-content/plugins/wp-healthcheck-rest/

Then create a plugin main file named wp-healthcheck-rest.php in the directory with the following content:

'GET', 'callback' => function () { return new WP_REST_Response(null, 204); }, 'permission_callback' => '__return_true', ]); });

This code does the following:

  • Register REST routes using the rest_api_init Hook;
  • The routing path is /wp-json/healthmonitor/check;
  • Set the request method to GET;
  • The response function directly returns a WP_REST_Response with empty content and a status code of 204;
  • Set permission_callback to __return_true, which means that the interface does not require permission verification and can be accessed by anyone.

After placing the plugin file in the wp-healthcheck-rest directory, log in to the WordPress backend and enable the plugin:

image.png

At this point, we have a stable, reliable, and standard-compliant live detection interface that is suitable for calls from various load balancers, monitoring systems, or automation platforms.

5 Actual effect verification

After the deployment is complete, you can directly use the browser to access the following address for verification:

http(s)://yourdomain/wp-json/healthmonitor/check

However, the result of using a browser to access the page is that the page disappears in a flash, which is not easy to take a screenshot. So, instead, you can use the simplest curl command to verify:

curl http(s)://yourdomain/wp-json/healthmonitor/check

You will now see the terminalNo output:

image.png

Although it may seem that "nothing is returned", this is exactly HTTP 204 No Content Characteristics - The request is successful, but the serverExplicitly indicates that there is no response bodyTo verify this, we can add the -i parameter to view the response header information:

curl -i http(s)://yourdomain/wp-json/healthmonitor/check

The returned content is as follows:

image.png

Several key points can be seen from the output:

  • HTTP status code is 204, indicating that the request is processed successfully, but no content is returned;
  • The response body is indeed empty, you will not see any text in the terminal, and the cursor will end directly on the new line;
  • The response header may contain fields such as Set-Cookie and Cache-Control, which reflect the actual service operation environment but do not affect the "blankness" of the body.

Before using this REST route, my blog used a custom page /healthcheck As a live interface, we also use the same method to compare its performance, using the simplest curl command, and a large amount of HTML content is directly output to the terminal (the following is only a screenshot of the first page, there are more than ten pages behind, so I won’t screenshot them one by one):

image.png

Let's look at the output with the response header-i, there are more than ten pages of output, this is the first page:
image.png

While this can technically be used for liveness detection, it has several obvious problems:

  • The returned HTTP 200, semantics that are not designed for exploration;
  • The response body is a complete HTML page, which, even if very simple, is much more bloated than a 204 response;
  • Theme templates, cache, SEO plugins, etc. may affect the returned content and bring unpredictable variables;
  • Some anti-aliasing tools or health checking systems (such as Cloudflare's health check) willMisjudgment of abnormal page content, which leads toFalse positives, which I used before/healthcheckpage is deeply affected;
  • Integration in systems such as operation and maintenance platforms and load balancers is also not "semantically clear" enough.

In contrast, the 204 response returned by /wp-json/healthmonitor/check is very clean, precise, and reliable, fully complying with the requirements of "No side effect detection interface"It does not return any response body, and the status code clearly expresses "the service is online but no content needs to be returned", which makes it bothAvoid being cached by static caching mechanisms such as Cloudflare APO and WordPress cache plugins, while minimizing the waste of bandwidth and response time, it is a purer and more stable form of health check.

6 Conclusion

At first glance, the liveness detection interface may seem like an insignificant detail, but it is actually often a cornerstone in the evolution of the architecture. Especially when we start using Cloudflare Tunnel as the entry point, GitHub Actions for automatic releases, and third-party monitoring services to detect liveness, a "clear and high-quality liveness detection path" becomes indispensable.

This article starts with the actual performance of common WordPress pages for health checks, points out some of its inadequacies as a live interface, and then through customizationregister_rest_route()"Registered a side effect-free"/wp-json/healthmonitor/check" path, so that it strictly returns 204 No Content, no body, no cache interference, no ambiguity, and fully complies with the common standards for live interfaces in modern web services.

More importantly, this design approach is well-suited for integration into an overall architecture that integrates automation, edge computing, and caching. For example, Cloudflare APO doesn't cache responses with a 204 status code, and local cache plugins like WP Super Cache can prevent these pages from being accidentally cached. Furthermore, tools like curl can be easily integrated, freeing CI/CD detection steps from tedious HTML or JSON parsing. And in the future, integration with load balancers or container orchestration platforms (such as Kubernetes' readinessProbe) will also be seamless, requiring no additional adaptation.

Of course, this liveness detection API concept is primarily designed for dynamic websites. If your site is already completely static, or even deployed on a platform like Cloudflare Pages, there's no need to design additional liveness detection logic—the CDN's inherent availability monitoring is sufficient for fault detection.

📌 Content Structure Hints:
This content belongs to "Blog Knowledge MapThis is part of the document; you can view the full content path here: Blog Knowledge Map .
Share this article
All blog content is original; please indicate the source when reprinting! The blog's RSS address is:https://blog.tangwudi.com/feed, welcome to subscribe; if necessary, you can joinTelegram GroupDiscuss the problem together.
No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠(ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ°Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
Emoticons
Emoji
Little Dinosaur
flower!
Previous
Next