Giter Site home page Giter Site logo

vigetlabs / redirector Goto Github PK

View Code? Open in Web Editor NEW
83.0 27.0 36.0 174 KB

A Rails engine that adds a piece of middleware to the top of your middleware stack that looks for redirect rules stored in your database and redirects you accordingly.

License: MIT License

Ruby 93.30% JavaScript 1.23% CSS 1.05% HTML 4.43%

redirector's Introduction

Redirector

Code Climate Build Status Coverage Status Gem Version

Redirector is a Rails engine that adds a piece of middleware to the top of your middleware stack that looks for redirect rules stored in your database and redirects you accordingly.

Install

  1. Add this to your Gemfile and then bundle install:

    gem 'redirector'
  2. $ rake redirector_engine:install:migrations

  3. $ rake db:migrate

  4. Create an interface for admins to manage the redirect rules.

Config options

include_query_in_source: If you want your redirect rules to also match against the query string as well as the path then you need to set this to true (the default is false).

silence_sql_logs: This option silences the logging of Redirector related SQL queries in your log file.

preserve_query: Pass the query string parameters through from the source to the target URL.

ignored_patterns: Lets you define an array of regex patterns which will be ignored when searching for redirect records. ie: [/^\/assets\/.+/] will bypass a database lookup for any path that starts with /assets/. This can be useful in preventing numerous unnecessary lookups.

You can set these inside your configuration in config/application.rb of your Rails application like so:

module MyApplication
  class Application < Rails::Application
    # ...

    config.redirector.include_query_in_source = true
    config.redirector.silence_sql_logs = true
    config.redirector.ignored_patterns = [/^\/assets\/.+/]
  end
end

Redirect Rule definitions

Redirect rules have 3 parts:

  1. A Source
  2. A Destination
  3. Request environment conditions

The source defines how to match the incoming request path and the destination is where to send the visitor if the match is made. A source can be a strict string equality match or it can be a regular expression that is matched. If a regular expression is used and it uses groupings, you can reference those groupings inside of the destination. For instance a regex like /my_custom_path\/([0-9]+)/ could use that grouping in the destination like this "/my_destination/$1". So, if the request path was "/my_custom_path/10" then the destination for that rule would be "/my_destination/10".

Redirect rules can also have further Rack/HTTP environment (mainly HTTP headers) conditions via RequestEnvironmentRules. These define a key in the rack environment passed into the middleware and a value match you require for the redirect rule it's tied too. Similar to the redirect rules these RequestEnvironmentRules can be string matches or regex matches. A redirect rule can have as many of these environment rules as you need.

When using regex matching on either a redirect rule source or a request environment rule environment value you can specify if you want the matching to be case sensitive or case insensitive with a boolean column that's on the table.

Schema Definition

Here's the schema definition used for the two tables:

create_table "redirect_rules", :force => true do |t|
  t.string   "source",                                      :null => false # Matched against the request path
  t.boolean  "source_is_regex",          :default => false, :null => false # Is the source a regular expression or not
  t.boolean  "source_is_case_sensitive", :default => false, :null => false # Is the source regex cas sensitive or not
  t.string   "destination",                                 :null => false
  t.boolean  "active",                   :default => false                 # Should this rule be applied or not
  t.datetime "created_at",                                  :null => false
  t.datetime "updated_at",                                  :null => false
end

create_table "request_environment_rules", :force => true do |t|
  t.integer  "redirect_rule_id",                                       :null => false
  t.string   "environment_key_name",                                   :null => false # Name of the enviornment key (e.g. "QUERY_STRING", "HTTP_HOST")
  t.string   "environment_value",                                      :null => false # What to match the value of the specified environment attribute against
  t.boolean  "environment_value_is_regex",          :default => false, :null => false # Is the value match a regex or not
  t.boolean  "environment_value_is_case_sensitive", :default => true,  :null => false # is the value regex case sensitive or not
  t.datetime "created_at",                                             :null => false
  t.datetime "updated_at",                                             :null => false
end

Databases supported

  • MySQL
  • PostgreSQL

If you require support for another database, the only thing that needs to be added is a definition for a SQL regular expression conditional (see app/models/redirect_rule.rb). If you create a pull request that adds support for another database, it will most likely be merged in.

Contributing to Redirector

  • Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
  • Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
  • Fork the project.
  • Start a feature/bugfix branch.
  • Commit and push until you are happy with your contribution.
  • Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
    • We're using Appraisal to test against different Rails versions.
    • In order to run the tests you'll need to do the following:
      1. cp spec/dummy/config/database.yml.example spec/dummy/config/database.yml
      2. modify that spec/dummy/config/database.yml with your mysql configuration details
      3. run appraisal install (should only need to do this once)
      4. run appraisal rake spec
  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright

Copyright (c) 2012 Brian Landau (Viget). See MIT_LICENSE for further details.


Code At Viget

Visit code.viget.com to see more projects from Viget.

redirector's People

Contributors

aldesantis avatar artfuldodger avatar brianjlandau avatar dependabot[bot] avatar fastjames avatar golddiga avatar jmarquis avatar mackermedia avatar phlipper avatar shostakovich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

redirector's Issues

Deprecation Warning of match_for method in Rails 5.2

Since Rails 5.2 calls of match_for are throwing the following deprecation warning:

DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s): "redirect_rules.source_is_regex ASC, LENGTH(redirect_rules.source) DESC". Non-attribute arguments will be disallowed in Rails 6.0. This method should not be called with user-provided values, such as request parameters or model attributes. Known-safe values can be passed by wrapping them in Arel.sql().

Add ability to filter by HTTP verbs

We have a route

resources :widgets

It produces the routes:

widgets GET      /widgets(.:format)             widgets#index
widgets POST     /widgets(.:format)             widgets#create
 widget PATCH    /widgets/:id(.:format)         widgets#update
        PUT      /widgets/:id(.:format)         widgets#update
        DELETE   /widgets/:id(.:format)         widgets#destroy

We want to redirect GET /widgets, but we want to keep POST /widgets and the others. Since the redirect rules do not consider HTTP verbs, we are faced with the problem of either,

  1. Not redirecting /widgets, or,
  2. Losing all the other endpoints

If there was an HTTP Verb column+filter, then we could micromanage this better.

Remove cached redirect

After disabling or removing redirect rules "old" user still have cached redirect in response "301 Moved Permanently (from disk cache)". Do you have any advice on how to get around this? Thanks!

Versioned migration doesn't work with Rails 4 (undefined method `[]' for #<ActiveRecord::Migration>

Hi,

The migrations define a Rails version. However, this leads to a NoMethodError: undefined method [] for #<ActiveRecord::Migration> when installing the gem with Rails 4.2.

The solution is to remove the [4.2] suffix from the 2 migration files.

So:
class CreateRedirectRules < ActiveRecord::Migration[4.2]
becomes:
class CreateRedirectRules < ActiveRecord::Migration

Btw, it comes from this commit. Since then, build is failing.

Cheers

Performance

I have about 1500 redirects with regexs and redirector made my app significantly slower because of querying database each request. Maybe it would be great to implement some cache.

I moved to https://github.com/jtrupiano/rack-rewrite for this amount of redirects.

No criticism of this gem, it may have good use cases when you need to build up db of redirects or you run very small app ... I'm just leaving note here for someone in situation when set of redirects is larger and finished ...

https URL is redirecting to http

I noticed that when I set up a redirect using the redirector gem that a source URL prefixed with https will redirect to the destination URL prefixed with http. I noticed this after I migrated to this gem from the define redirects in my Rails routes file.

Is there a way to make it redirect to https?

redirector.silence_sql_logs = true change log level to 3 in production

Configuring the app like it sais in README.md, in production environment initialized with log level to 1 (:info), sometimes the app changes the log level to 3 (:error).

I detect that making some simultaneous in ajax petitions on the app generates this error. To return the log level to :info I have to restart the app to get the setting initialization.
The error is produced inside class Responder from Middleware, in with_optional_silencing method

To get by with the error, I configured de redirector.silence_sql_logs to true only in development environment. I don't know why still works in development, but in this environment doesn't change.
In production if silence_sql_logs is set to false and logger level is initialized to 3 (:info) the redirector sql logs aren't showed (that is what I want).

Only execute queries on 404

I'm using this gem, very helpful, but noticed that it executes the queries for every request rails receives, which means an extra DB query for every request.

I think it could be made so that it only executes when a 404 is found (no route matches), and then, and only then look for a redirect rule, this would reduce the number unnecessary of DB queries.

I'm not in a position to code this, I'm just learning Ruby, Rails and Rack work.

Getting error in production

2015-04-17 09:35:02 +0000: Rack app error: #<ArgumentError: wrong number of arguments (0 for 1)>
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/activesupport-4.1.9/lib/active_support/core_ext/kernel/reporting.rb:82:in `capture'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/redirector-1.0.1/lib/redirector/middleware.rb:43:in `with_optional_silencing'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/redirector-1.0.1/lib/redirector/middleware.rb:36:in `matched_destination'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/redirector-1.0.1/lib/redirector/middleware.rb:32:in `redirect?'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/redirector-1.0.1/lib/redirector/middleware.rb:22:in `response'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/redirector-1.0.1/lib/redirector/middleware.rb:10:in `call'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/activesupport-4.1.9/lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/actionpack-4.1.9/lib/action_dispatch/middleware/static.rb:84:in `call'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:136:in `forward'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:245:in `fetch'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:185:in `lookup'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:66:in `call!'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:51:in `call'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/railties-4.1.9/lib/rails/engine.rb:514:in `call'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/railties-4.1.9/lib/rails/application.rb:144:in `call'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/puma-2.11.1/lib/puma/configuration.rb:82:in `call'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/puma-2.11.1/lib/puma/server.rb:507:in `handle_request'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/puma-2.11.1/lib/puma/server.rb:375:in `process_client'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/puma-2.11.1/lib/puma/server.rb:262:in `block in run'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/puma-2.11.1/lib/puma/thread_pool.rb:104:in `call'
/home/ubuntu/apps/connectica/shared/bundle/ruby/2.2.0/gems/puma-2.11.1/lib/puma/thread_pool.rb:104:in `block in spawn_thread'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.