TIL #2: How to Always Include Language Code in Your Rails App URLs

Photo of Marcin Szmigiel

Marcin Szmigiel

Dec 20, 2017 • 2 min read

In today's TIL...

Ruby on Rails!

When you're developing the multi-language application at some point you may encounter the need to always include language code in your URLs.

The same happened to me and I found one extremely simple trick that will allow you to:

1. Always have language code in your URLs.

2. Redirect user to correct URL when someone tried to reach your app without language code given.

All you need to do is change slightly your config/routes.rb. Here you go:

# config/routes.rb

MyApp::Application.routes.draw do
  scope "/:locale", locale: /#{I18n.available_locales.join("|")}/ do
    # your routes go here
    root to: "home#index"
  root to: redirect("/#{I18n.default_locale}", status: 302), as: :redirected_root
  get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302),
                constraints: { path: /(?!(#{I18n.available_locales.join("|")})\/).*/ },
                format: false

Simple, isn't it?

TIL, or Today I Learned, is where our developers share the best tech stuff they found every day. You can find smart solutions for some issues, useful advices and anything which will make your developer life easier.

Photo by Sara Riaño on Unsplash

Photo of Marcin Szmigiel

More posts by this author

Marcin Szmigiel

Marcin has a mix of scientific and humanistic mind, that’s why he chose to study Human-Computer...
How to build products fast?  We've just answered the question in our Digital Acceleration Editorial  Sign up to get access

We're Netguru!

At Netguru we specialize in designing, building, shipping and scaling beautiful, usable products with blazing-fast efficiency
Let's talk business!

Trusted by:

  • Vector-5
  • Babbel logo
  • Merc logo
  • Ikea logo
  • Volkswagen logo
  • UBS_Home