How do I tell Nginx to wait a number of seconds before serving an asset?

So when I'm locally testing things such as Ajax in apps I'm writing, I often like to add a delay in server side scripts using a sleep statement. It helps simulate slow connections etc.

Is there a way to specify a similar delay behaviour directly in Nginx config that would work for the flat HTML files it's serving?

I'm aware you can do a similar delay simulation at the network level (see here) but it seems pretty messy and has never worked very well for me.


You should try an echo module.

  • https://www.nginx.com/resources/wiki/modules/echo
  • https://github.com/openresty/echo-nginx-module#readme

Giving a more detailed explanation of how you might use the echo module:

If you're starting from a basic config, that loads static files and PHP files, with something like this:

location ~ \.php$ {
    include fastcgi.conf;
    fastcgi_pass php;
}

That can then be converted to something like this to add a delay to both static and PHP requests:

# Static files
location / {
    echo_sleep 5;
    echo_exec @default;
}
location @default {}

# PHP files
location ~ \.php$ {
    echo_sleep 5;
    echo_exec @php;
}
location @php {
    include fastcgi.conf;
    fastcgi_pass php;
}

This can obviously be modified for anything you want. Basically, move each location block into a named @location. Then use echo_sleep and echo_exec in the original location block.