Skip to content

Instantly share code, notes, and snippets.

@waissbluth
Last active July 27, 2022 17:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save waissbluth/db93443d87c67391f677 to your computer and use it in GitHub Desktop.
Save waissbluth/db93443d87c67391f677 to your computer and use it in GitHub Desktop.
Ruby on Rails SEO. Add a <link rel="alternate" hreflang="es" href="http://es.example.com/" /> link to every other locale for the same page. Per https://support.google.com/webmasters/answer/189077?hl=en
-# For each locale except the current one
- (I18n.available_locales - [I18n.locale]).each do |locale|
-# Add a link to the current URL but in `locale` language
%link{rel: 'alternate', hreflang: locale, href: url_for(locale: locale)}
@joshforeman
Copy link

Hey @waissbluth - are you including this partial into your layout?

Could you share your url_for helper method.

Thanks

@bovender
Copy link

bovender commented May 8, 2017

@joshforeman, it's several months since you asked this, but maybe still of interest: this belongs into the <head>...</head> section of your site. I'd suggest not subtracting [I18n.locale] though because per Google's definition, the current page needs to link back to itself:

If you have multiple language versions of a URL, each language page should identify different language versions, including itself.

In addition, you may want to add only_path: false in order to get absolute URLs:

-# For each locale except the current one
- I18n.available_locales.each do |locale|
  -# Add a link to the current URL but in `locale` language
  %link{rel: 'alternate', hreflang: locale, href: url_for(locale: locale, only_path: false)}

url_for is a Rails method.

I use the above code with a Rails 5.1.0 application.

@trantorLiu
Copy link

trantorLiu commented Aug 11, 2017

@bovender Thank you for the very useful info!

@IlkhamGaysin
Copy link

You also should add x-default to get default page when there won't any matched page.

- # It will be taken when no one of the available_locales will be relevant.

%link{rel: 'alternate', hreflang: 'x-default', href: url}
- I18n.available_locales.each do |locale|
  %link{rel: 'alternate', hreflang: locale, href: url_for(locale: locale, only_path: false)}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment