Question

A site I manage is getting constant requests for a javascript file that no longer exists, from an older version of the site. These requests take up a lot of resources because they get routed through Rails every time to return a 404. I am thinking it would be much better to have Rack handle that specific URL and return 404 itself. Is that correct? If so, how would I set that up?

I have been checking out this blog post which I think is kinda the way to move forward (ie, inheritance from some existing Rack module):

http://icelab.com.au/articles/wrapping-rack-middleware-to-exclude-certain-urls-for-rails-streaming-responses/

Was it helpful?

Solution

So I ended up writing my own little bit of middleware:

module Rack

  class NotFoundUrls

    def initialize(app, exclude)
      @app = app
      @exclude = exclude
    end

    def call(env)

      status, headers, response = @app.call(env)

      req = Rack::Request.new(env)
      return [status, headers, response] if !@exclude.include?(URI.unescape(req.fullpath))

      content = 'Not Found'
      [404, {'Content-Type' => 'text/html', 'Content-Length' => content.size.to_s}, [content]]

    end

  end

end

and then adding this to the config.ru file:

use Rack::NotFoundUrls, ['/javascripts/some.old.file.js']

It's the first time I've done this so let me know if there's any glaring mistakes...

OTHER TIPS

The rack-contrib gem includes a Rack::NotFound middleware component (among many other useful elements) which should do the job:

https://github.com/rack/rack-contrib/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top