Last active
July 27, 2022 17:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-# 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, 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.
@bovender Thank you for the very useful info!
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
Hey @waissbluth - are you including this partial into your layout?
Could you share your url_for helper method.
Thanks