Serhii Danovskyi
Serhii Danovskyi

Reputation: 394

Rails 301 Redirection from /de to /de/

How I can make redirect from

http://bla.com/de to http://bla.com/de/

I tried

get '/de', to: redirect('de/', status: 301)


get "/de" => redirect("/de/")

But I have an error error: Too many redirects

Where are my mistake ?

 [Anonymous user] Started GET "/de" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200

Upvotes: 0

Views: 75

Answers (1)

Rohan
Rohan

Reputation: 2727

First, rails do not distinguish between a forward slash or a trailing slash. That is why you are getting too many redirects error.

One way to achieve this could defining a method in ApplicationController and then using it as a filter to redirect your requests

def force_trailing_slash
    redirect_to request.original_url + '/' unless request.original_url.match(/\/$/)
end

Or you can use rack-rewrite to perform the same task in your Rails app at Rack level.

https://github.com/jtrupiano/rack-rewrite

config.middleware.insert_before 0, Rack::Rewrite do
  r301 '/de', '/de/'
end

Another way which could help would be:

get '/de', :to => redirect('de/'), :constraints => lambda {|r| !r.original_fullpath.end_with?('/')}

Hope this helps!!

Upvotes: 1

Related Questions