Nginx + Passenger: Cache 404 urls

The context

I have a Rails application with a Nginx server and Passenger.

The application dynamically generates pages from the URL of the application: if the URL exists in the database, the application displays the corresponding page. Or if the URL does not exist in the database, the application displays a page 404.

Problem

Many robots try to find vulnerabilities and ask a lot of URLs (.git, admin / config.php, wp-login.php etc …)

Each of these requests reaches the Rails application, which generates hits in the database.

Solution

I'm looking for a way to do that:

  1. For the first time, a "non-existent" URL, if requested, goes through the Rails application, which responds with a 404
  2. nginx hide and remember this URL
  3. the next time the same URL is requested, nginx responds directly with the 404 status without going through the Rails application

Similarly, when the Rails application is restarted (via Passenger), this cache must be purged.

testing

  • I've tried to add fastcgi_cache_valid 404 10m; in the server block, it does not work.
  • Also tried proxy_cache_valid 404 10m;

As you can guess, I am new to nginx.
Thank you for your help.