Score:0

Rate limit specific PHP endpoints when running Nginx with php-fpm

in flag

Like many apps, I have some endpoints that are more sensitive than others, such as login & password reset, and need rate limiting. However, nginx handles all requests for PHP resources through a standard location handler that proxies PHP-FPM:

  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_index index.php;
    fastcgi_pass php80;
  }

This means that I can't also use location directives to match my sensitive endpoints as it will prevent them being passed on to PHP.

For example, if I define a rate limit and use it in a location for the login URL:

limit_req_zone $binary_remote_addr zone=sensitive:2m rate=3r/m;
location /login {
    limit_req zone=sensitive burst=3 nodelay;
}

It will rate limit the requests to that endpoint, but they will no longer be processed by PHP.

I could do a dumb copy/paste and have this kind of thing for every endpoint:

location /login {
    limit_req zone=sensitive burst=3 nodelay;
    try_files $uri =404;
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_index index.php;
    fastcgi_pass php80;
}

but I'm sure there's a better way.

How should I define rate limits inside the PHP location directive?

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.