Skip to content

A platform for community discussion. Free, open, simple.

FIX: Use hyphens instead of underscores for hreflang tags (#39884)

asa0w0d5b6f5753d53
diff --git a/app/views/common/_hreflang_tags.html.erb b/app/views/common/_hreflang_tags.html.erb
index 3efd3945ab8..0302db2fa9b 100644
--- a/app/views/common/_hreflang_tags.html.erb
+++ b/app/views/common/_hreflang_tags.html.erb
@@ -5,7 +5,7 @@
<% canonical_url = "#{Discourse.base_url}#{current_path}" %>
<link rel="alternate" href="<%= canonical_url %>" hreflang="x-default" />
<% locales.each do |locale| %>
- <link rel="alternate" href="<%= canonical_url %>?<%= Discourse::LOCALE_PARAM %>=<%= locale %>" hreflang="<%= locale %>" />
+ <link rel="alternate" href="<%= canonical_url %>?<%= Discourse::LOCALE_PARAM %>=<%= locale %>" hreflang="<%= locale.tr('_', '-') %>" />
<% end %>
<% end %>
<% end %>
diff --git a/spec/requests/crawler_hreflang_spec.rb b/spec/requests/crawler_hreflang_spec.rb
index 705f658d456..83efacc077a 100644
--- a/spec/requests/crawler_hreflang_spec.rb
+++ b/spec/requests/crawler_hreflang_spec.rb
@@ -25,6 +25,23 @@ describe "Crawler hreflang tags" do
expect(response.body).to include("?#{Discourse::LOCALE_PARAM}=ja")
end
+ it "uses hyphens instead of underscores in hreflang attribute for region-qualified locales" do
+ SiteSetting.content_localization_supported_locales = "en|pt_BR|zh_CN"
+
+ get "/t/#{post.topic.slug}/#{post.topic.id}",
+ headers: {
+ "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)",
+ }
+
+ expect(response.body).to include('hreflang="pt-BR"')
+ expect(response.body).to include('hreflang="zh-CN"')
+ expect(response.body).not_to include('hreflang="pt_BR"')
+ expect(response.body).not_to include('hreflang="zh_CN"')
+
+ expect(response.body).to include("?#{Discourse::LOCALE_PARAM}=pt_BR")
+ expect(response.body).to include("?#{Discourse::LOCALE_PARAM}=zh_CN")
+ end
+
it "doesn't include hreflang tags for normal users" do
get "/t/#{post.topic.slug}/#{post.topic.id}"