skip to Main Content

I submitted my sitemap to google as example.com/sitemap where example.com is my domain Watching my server access log requests come in for sitemap.txt and sitemap.xml Can I just add routes for sitemap.txt and sitemap.xml for a total of 3 routes to the same controller action? I thought of "redirect" but I don’t think it applies

What should I do with requests for sitemap.xml and sitemap.txt when I’m already serving requests to /sitemap

2

Answers


  1. yes you definitely can easily route to the same action, the file suffix (.xml, .txt, .html etc) is defined as a parameter in your routes file. So for example you might define a route like this:

    # config/routes.rb
    get 'sitemap(.:format)', to 'sitemap.index'
    

    In your SitemapController, the index method would receive a params hash that includes the :format key, with a value of ‘xml’, ‘txt’, ‘html’. Does that meet your needs?

    Login or Signup to reply.
  2. You don’t have to do anything. Rails will automatically handle extensions.

    Lets say you have one of these routes:

    # Both of these options generate the same routes
    get :sitemap, to: 'sitemaps#show'
    resource :sitemap, only: :show
    

    If you run rails routes -c sitemap you can see that it matches the pattern /sitemap(.:format).

     Prefix Verb URI Pattern        Controller#Action
    sitemap GET  /sitemap(.:format) sitemaps#show
    

    To respond to various formats you can either just create views for each format and use implicit rendering if what you’re doing is very simple:

    class SitemapsController < ApplicationController
      # GET /sitemaps.txt
      # GET /sitemaps.xml
      def show
        # this is optional but it can be good to enumerate which formats 
        # you should actually accept
        respond_to :txt, :xml
      end
    end
    

    This will render app/views/sitemaps/show.#{format}.html.erb.

    Or you can use MimeResponds to handle each type explicitly:

    class SitemapsController < ApplicationController
      # GET /sitemaps.txt
      # GET /sitemaps.xml
      def show
        respond_to do |format|
          format.txt { ... }
          format.xml { ... }
        end
      end
    end
    

    This can be a good idea if you’re for example generating the XML without a view. Or you can even do a mix by omitting the block.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search