如何使用 rails 和两个单独的主机名来实现 URL shortener?

How to implement URL shortener with rails with two separate hostname?

假设我有一个域 foobargoo.com,我最近注册了 fbg.co,这样我就可以添加 Url 缩写词。我可能有很多请求的路由 foobargoo.com/requests/:id 最终可能超过 100 个字符,我想使用 fbg.co/TxFj4 之类的东西(它提供 > 9 亿个字符串)并重定向到具体的ID。

我想知道我是否可以在 routes.rb 的一个 rails 代码库中完成它,或者我是否必须添加一个新的 repo 才能做到这一点?

把它放在一个代码库中似乎没问题。您当然 不需要 创建单独的项目,但您可能希望加快重定向速度(例如使用轻量级 Sinatra 项目而不是 Rails)。

在您的 routes.rb 中,您可以像这样添加缩短的路线:

constraints(host: 'fbg.co') do
  get ':id', to: 'shortener#redirect'
end

然后使用一个简单的操作来处理重定向:

# shortener_controller.rb

class ShortenerController < ApplicationController
  def redirect
    redirect_to ShortLink.find_by_hash(params[:id]).url
  end
end

当然,您需要一个模型来存储短 URL 并将它们映射到完整 URL:

class ShortLink
  # Migration for its creation is something like:
  #   t.string :hash
  #   t.string :path

  def url
    "foobargoo.com/#{path}"
  end
end