Sha256: 6776f647e0764f5f2930d51a890da865f077280e6263cca40de8682781a37b72

Contents?: true

Size: 1.08 KB

Versions: 18

Compression:

Stored size: 1.08 KB

Contents

# frozen_string_literal: true

module Koi
  module Middleware
    class UrlRedirect
      def initialize(app)
        @app = app
      end

      def call(env)
        status, headers, body = @app.call(env)

        current_path = env["REQUEST_URI"]

        if status.to_i == 404 && (redirect = UrlRewrite.active.find_by(from: current_path))
          request = ActionDispatch::Request.new(env)

          # Close the body as we will not use it for a 301 redirect
          body.close

          # Return a redirect response
          [redirect.status_code, { "Location" => new_location(current_path, redirect.to, request) },
           ["#{redirect.from} moved. The document has moved to #{redirect.to}"]]
        else
          # Not a 404 or no redirect found, just send the response as is
          [status, headers, body]
        end
      end

      private

      def new_location(current_path, new_path, request)
        if %r{\Ahttps{0,1}://}.match?(new_path)
          new_path
        else
          request.original_url.gsub(current_path, new_path)
        end
      end
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
katalyst-koi-4.14.1 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.14.0 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.13.2 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.13.0 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.12.6 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.12.5 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.12.4 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.12.3 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.12.2 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.12.1 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.12.0 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.11.2 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.11.1 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.11.0 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.10.3 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.10.2 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.10.1 lib/koi/middleware/url_redirect.rb
katalyst-koi-4.10.0 lib/koi/middleware/url_redirect.rb