Skip to content

Instantly share code, notes, and snippets.

@brentertz
Created July 11, 2012 22:45
Show Gist options
  • Save brentertz/3094260 to your computer and use it in GitHub Desktop.
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.
config.middleware.insert_before(0, 'Rack::SeoRedirect')
# 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
require 'seo_redirect'
use Rack::SeoRedirect
@brentertz
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment