问题
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