How to get a canonical url for a dynamically generated urls on rails?

╄→гoц情女王★ 提交于 2020-03-03 07:39:10

问题


I implemented canonical url for homepage as follows: I added this line

  <link rel='canonical' href='https://example.com/'> 

I added this line on index.html.erb in header section. It is working fine.

Now I have dynamic routes generating line as follows:

<a href "<%= search_equipments_path(:category_id => category.id) %>">

I tried with following:

<a rel='canonical' href="<%= search_equipments_path(:category_id => category.slug) %>">

But didn't work.


回答1:


We can set canonical tags in rails this way. This rails code will output canonical tags for full current url. Add this in layout in HTML head section.

 <link rel="canonical" href="<%= url_for(:only_path => false) %>" />

You can also specify the default protocol to be use for this URL by using:

<link rel="canonical" href="<%=url_for(:only_path => false, :protocol => 'https')" />

For more options please refer this link

Hope this helps.




回答2:


You can use content_for to create a dynamic chunk in the header section of your layout:

# app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    # ...
    <% if content_for?(:canonical_url) -%>
      <%= tag :link, href: content_for(:canonical_url), rel: 'canonical' %>
    <% end -%>
  </head>
</html>

You can then provide the canonical_url in your views:

<%= provide(:canonical_url, search_equipments_url(category.slug)) %>


来源:https://stackoverflow.com/questions/43434601/how-to-get-a-canonical-url-for-a-dynamically-generated-urls-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!