gpt4 book ai didi

ruby-on-rails - 在 Rails 3 中的区域设置更改后重定向到新域中的同一页面

转载 作者:数据小太阳 更新时间:2023-10-29 06:37:02 24 4
gpt4 key购买 nike

使用带有以下 gem 的 Rails 3.2.8 的应用程序

gem 'friendly_id', '~> 4.0'
gem 'route_translator'

在/config/initializers/i18n.rb

TLD_LOCALES = {
"com" => :en,
"jobs" => :en,
"net" => :en,
"in" => :en,
"de" => :de,
"ch" => :de,
"at" => :de,
"br" => :pt,
"ar" => :es,
"cl" => :es,
"mx" => :es
}

在/app/controllers/application_controller.rb 中,使用前置过滤器为每个请求设置语言环境:

before_filter :set_auto_locale
def set_auto_locale
I18n.locale = TLD_LOCALES[request.host.split('.').last]
end

在 routes.rb 中

localized do
match "label_vacancies/:view_job"=>"job_seekers#view_job"
get "label_aboutus", :to => "home#about_us", :as => "about_us"
end

当用户请求更改语言区域设置时,以下域应根据用户请求的区域设置加载。

在初始化器中

domain_based_on_locale = {
:en => "xxxxx.com",
:de => "xxxxx.de",
:es => "xxxxx.mx",
:pt => "xxxxx.com.br"
}

在/app/controllers/application_controller.rb

def set_manual_locale
if params[:locale] && I18n.available_locales.include?(params[:locale].to_sym)
cookies['locale'] = { :value => params[:locale], :expires => 1.year.from_now }
I18n.locale = params[:locale].to_sym
elsif cookies['locale'] && I18n.available_locales.include?(cookies['locale'].to_sym)
I18n.locale = cookies['locale'].to_sym
end
if domain_based_on_locale[I18n.locale] != request.host
redirect_to "#{request.protocol}#{domain_based_on_locale[I18n.locale]}#{request.fullpath}", :status => :moved_permanently
else
redirect_to root_path
end
end

在这种情况下,用户在如下 URL 中更改语言时会遇到重定向问题,因为同一页面根据语言具有不同的 URL。

Aboutus:
http://xxxxxxx.com/about-us # About us route in English
http://xxxxxxx.de/uber-uns # About us route in German
http://xxxxxxx.mx/quienes-somos # About us route in Spanish

view Job:
http://xxxxxxx.com/jobs/rp-be-company-representante-de-ventas-22042015
http://xxxxxxx.de/ofertas-de-empleo/rp-be-company-representante-de-ventas-22042015

手动更改语言区域后,如何重定向到新域中的同一页面。是否可以将正在运行的 session 带到新域。感谢您的帮助。

最佳答案

您需要翻译 request.fullpath 的每一段(最后一段除外,它看起来像资源段)。您可以使用 Rails 的 I18n 手动执行此操作:

current_path = request.fullpath.split('/')
slug = current_path.pop
locale_path = current_path.map{|part| translate(part)}.join('/')
redirect_to "#{request.protocol}#{domain}#{locale_path}#{slug}"

或者,有处理路由转换的 gem:

就 session 而言,跨域共享 cookie 本身是不可能的。如果您创建区域设置子域(例如 de.xxxxx.com),您可以 share the cookie across all of them .许多网站通过路径来做到这一点,例如。 xxxxx.com/de/,完全解决了这个问题。

支持完全不同的域需要您手动传输 session 。您可以通过类似的方式实现这一点:

  • 生成随机传输 token xxx123 并将其保存在服务器端及其附加的 session 中
  • 重定向到 new.domain/path?token=xxx123
  • 使用 token 查找用户的 session 并在他们的浏览器中设置
  • 删除 token 以防止重放攻击

请仔细考虑传输过程 - 执行此类操作时很容易引入安全问题。 This SO thread有一种方法使用从其他域加载的图像。

关于ruby-on-rails - 在 Rails 3 中的区域设置更改后重定向到新域中的同一页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29798006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com