Search code examples
ruby-on-railsnginxamazon-elastic-beanstalkpuma

In Nginx, how can I return 404s for specific URL pattern/regex without sending request to the app server?


I have an ruby on rails app (puma/nginx) and I'm having some issues with some requests that are hitting the app server and giving errors on my apps.

For example, this is a valid route for news article 123456:

/api/v1/news/123456

However I'm receiving lots of requests to the API like this:

/api/v1/news/apple-touch-icon.png

(and other static assets)

This of course is invalid and the app gives me error. I can validate in the code to only accept valid values, however the app still need to process these requests.

I was thinking if there is a way where in nginx I could configure a regex where everything that starts with /api/ and has anything like png, jpg, ico, xml, etc in the URL gives an 404 error without sending the request to the app server, and if possible to cache the response for a couple of minutes to easy the load.

How could I accomplish this?

Thanks!


Solution

  • location ~ ^/api/.*\.(png|jpg|ico|xml)$ {
        return 404;
    }
    

    You can not speed it up by caching, it's very fast.