1

I've got an nginx config for a PHP web app and I would like to make it serve an additional purpose, and I can't seem to find a way to accomplish it. My current nginx config does the following:

  • Rewrites / and /intro/* to static HTML pages for a non-PHP powered "marketing" site
  • Attempts to load /maintenance.html if present on disk, which only exists during deploys
  • If /maintenance.html does not exist, sends requests to PHP via FastCGI

The end result is that the static pages remain available during deploys, and the back end PHP app can go down for maintenance while deploys happen. The important portion of the server config block looks like:

rewrite ^/$ /marketing/index.html last;
rewrite ^/intro/(.*)$ /marketing/$1.html last;

try_files $uri /maintenance.html @webapp;
location @webapp
{
    rewrite ^(.*)$ /index.php?url=$1 last;
}

include php.conf;

(php.conf config handles location ~ \.php$ locations and does all the usual fastcgi_param setting. Nothing project-specific there, so I didn't post that block.)

What I would like to be able to do in addition to the above is when "maintenance mode" is on, serve up /maintenance.html for standard HTTP requests, but respond with some JSON when handling AJAX requests. I've found that I can safely return rudimentary content by doing:

if ($http_x_requested_with = XMLHttpRequest)
{
    return 503 '{"maintenance":true}';
}

However, this obviously happens for all requests, not just those where /maintenance.html is being served. It seems I will need some flag somewhere, since try_files doesn't let you do additional things depending on which file or location it selected.

Is there some way nginx can be configured to return both HTML and JSON maintenance mode details?

Edit: Thinking about it more, it would be nice to perhaps move maintenance.html out of try_files completely, so that it can be served with a 503 status instead of a 200.

1
  • I'm very interested in this too - We have a similar situation, except it's with an Express server for a prototype application. It has a few html endpoints for whitebox-style viewing, but the primary routers are JSON API style endpoints. I've been trying to figure out a way to have nginx return standard error pages for html, and then a standard JSON response for any POST requests with the json content-type, but I've had no luck so far. If you have any tips on how to do this, I'm very keen to hear! Jun 30, 2017 at 2:23

0

You must log in to answer this question.

Browse other questions tagged .