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

Solution 1:

You should try an echo module.

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

Solution 2:

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.


Solution 3:

I would like to add to astlock's answer that if you want to reply with a plain return then note that there's a caveat: you have to use echo, not a standard return directive, after echo_sleep to respond with a delay, like this:

location = /slow-reply {
  echo_sleep 5.0;
  #return 200 'this response would NOT be delayed!';      
  echo 'this text will come in response body with HTTP 200 after 5 seconds';
}

(Tested on openresty/1.7.10.2)

Tags:

Nginx