Created
July 11, 2012 22:45
-
-
Save brentertz/3094260 to your computer and use it in GitHub Desktop.
Rack middleware to help avoid SEO duplicate content issues. Removes www and trailing slash and performs a permanent redirect.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
config.middleware.insert_before(0, 'Rack::SeoRedirect') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Avoid SEO duplicate content issues | |
# - Remove www from domain | |
# - Remove trailing slash | |
module Rack | |
class SeoRedirect | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
request = Rack::Request.new env | |
url = request.url | |
url.sub!('//www.', '//') if request.host =~ /^www\./ | |
url.chomp!('/') if request.path_info =~ %r{^/(.*)/$} | |
if url != request.url | |
[301, { 'Location' => url, 'Content-Type' => 'text/html' }, []] | |
else | |
@app.call env | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'seo_redirect' | |
use Rack::SeoRedirect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Associated blog post --> http://quickleft.com/blog/avoiding-seo-duplicate-content-issues-with-ruby-and-rack-middleware--2