nginx,

Return a status code 200 with a custom header in Nginx

May 15, 2023 · 1 min read · Post a comment

It might be useful sometimes for troubleshooting purposes to return a custom header from a Nginx server block. Here’s how to do it.

Prerequisites

  • Nginx

Solution

Open the Nginx config and you can have something like this for instance:

server {
    listen 80;
    server_name devcoops.com;

    location / {
        add_header Custom-Header "Return custom header";
        return 200;
    }
}

Since there is no content type set it assumes it’s a plain text. However, if you want to return a response in a JSON format, you could add the following instead:

server {
...
    location / {
        add_header Custom-Header "Return custom header";
        add_header Content-Type "application/json";
        return 200;
    }
}

As always, don’t forget to test your nginx config by running: nginx -t, and systemctl reload nginx.

Conclusion

In case you face any issues, feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.