繁体   English   中英

如何使用Rack中间件返回特定URL的404

[英]How can I return a 404 for a specific URL with Rack middleware

我管理的网站从旧版本的网站获得对不再存在的javascript文件的持续请求。 这些请求占用了大量资源,因为它们每次都通过Rails路由返回404.我认为让Rack处理特定的URL并返回404本身会好得多。 那是对的吗? 如果是这样,我该如何设置?

我一直在查看这篇博文,我认为这有点像前进的方式(即从一些现有的Rack模块继承):

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

所以我最终编写了自己的一些中间件:

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

然后将其添加到config.ru文件:

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

这是我第一次这样做,所以让我知道是否有任何明显的错误......

rack-contrib gem包含一个Rack::NotFound中间件组件(以及许多其他有用的元素),它们可以完成这项工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM