user3576036
user3576036

Reputation: 1425

How to send a specific url pattern to 404 in rails application?

In my rails application I am generating a url, whose proper pattern is as follows:

https://example.com/equipment_details/slug

This is the url google is supposed to be indexing. But due to pagination implementation using javascript there is another active url on platform as follows:

http://localhost:3000/equipment_details/slug?page=2.

controller method is like below:

class EquipmentsController < ApplicationController
  def equipment_details
    @equipment = Equipment.friendly.active.includes(:country, :manufacturer, :category, :user).find(params[:id])
    if @equipment
      @products = @equipment.category.equipments.active.where.not("equipment.id = ?", @equipment.id)
      @countries = Country.active.all
      @states = State.active.all
      @cities = City.active.all
      @services = Service.active.where("category_id = ? AND sub_category_id = ? AND country_id = ? AND state_id = ? AND city_id = ?", @equipment.category_id, @equipment.sub_category_id, @equipment.country_id, @equipment.state_id, @equipment.city_id)
      respond_to do |format|
        format.js
        format.html
        format.pdf do
          render :pdf => "vendaxo_#{@equipment.title}",
                 :layout => 'equipment_details_pdf.html.erb',
                 :disposition => 'attachment'
        end
      end
    else
      flash[:error] = "Equipment not found."
      redirect_to root_path
    end
  end
end

Basically the main content on both url is same except for the javascript pagination content in the footer. This is causing issues in SEO optimization. How can I send the url with second pattern i.e the uel with ?page=2 to 404 page ? Is there a way to do it from rails routes file?

Upvotes: 0

Views: 45

Answers (2)

murb
murb

Reputation: 1860

You could send a 404 using when params[:page] == 2:

render plain: "record was not found", status: :not_found

However, you shouldn't simply send a 404 when you don't want Google to index the page (that actually does exist). Google evaluates javascript these days as well.

Consider adding a noindex header to the page and/or use a canonical url reference:

<meta name="robots" content="noindex">
<link rel="canonical" href="https://example.com/equipment_details/name">

Upvotes: 0

nicohvi
nicohvi

Reputation: 2270

If you specifically want to look for a query parameter called page and raise an exception to activate the 404 response (if that request isn't an AJAX call from your javascript), you can do that in a before action in your EquipmentDetailsController (or whatever it's called).

class EquipmentDetailsController < ApplicationController
  before_action :send_to_404, only: [:name] # or whatever the action is called

  def send_to_404
    if !request.xhr? && !params[:page].nil?
      raise ActionController::RoutingError.new('Not Found')
    end
  end  
end

Upvotes: 1

Related Questions