rails中子域的多个robots.txt

Chr*_*her 8 ruby ruby-on-rails

我有一个包含多个子域的站点,我希望命名的子域robots.txt与www一个不同.

我尝试使用.htaccess,但FastCGI不看它.

所以,我试图设置路由,但似乎你不能直接重写,因为每个路由都需要一个控制器:

map.connect '/robots.txt', :controller => ?, :path => '/robots.www.txt', :conditions => { :subdomain => 'www' }
map.connect '/robots.txt', :controller => ?,  :path => '/robots.club.txt'
Run Code Online (Sandbox Code Playgroud)

解决这个问题的最佳方法是什么?

(我正在使用子域的request_routing插件)

小智 17

实际上,您可能希望设置一个mime类型mime_types.rb并在一个respond_to块中执行它,因此它不会将其返回为'text/html':

Mime::Type.register "text/plain", :txt
Run Code Online (Sandbox Code Playgroud)

然后,您的路线将如下所示:

map.robots '/robots.txt', :controller => 'robots', :action => 'robots'
Run Code Online (Sandbox Code Playgroud)

对于rails3:

match '/robots.txt' => 'robots#robots'
Run Code Online (Sandbox Code Playgroud)

和这样的控制器(把文件放在你喜欢的地方):

class RobotsController < ApplicationController
  def robots
    subdomain = # get subdomain, escape
    robots = File.read(RAILS_ROOT + "/config/robots.#{subdomain}.txt")
    respond_to do |format|
      format.txt { render :text => robots, :layout => false }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

冒着过度工程的风险,我甚至可能会想要缓存文件读取操作......

哦,是的,你几乎肯定要删除/移动现有'public/robots.txt'文件.

细心的读者会发现,你可以很容易地替换RAILS_ENVsubdomain...

  • 感谢发布此内容,这激发了我的灵感 - 我简化了这项技术并更新了Rails 3. http://www.timbabwe.com/2011/08/rails-robots-txt-customized-by-environment-automatically/ (3认同)

ram*_*igg 10

为什么不使用视图中内置的rails?

在您的控制器中添加此方法:

class StaticPagesController < ApplicationController
  def robots
    render :layout => false, :content_type => "text/plain", :formats => :txt
  end
end
Run Code Online (Sandbox Code Playgroud)

在视图中创建一个文件:app/views/static_pages/robots.txt.erbwith robots.txt content

routes.rb地方:

get '/robots.txt' => 'static_pages#robots'
Run Code Online (Sandbox Code Playgroud)

删除文件 /public/robots.txt

您可以根据需要添加特定的业务逻辑,但这样我们就不会读取任何自定义文件.