Rails - 确保 www 在 URL 中 [英] Rails - Ensuring www is in the URL
问题描述
我的应用程序托管在 Heroku 上,并且拥有 www.mysite.com 的证书
I have my app hosted on Heroku, and have a cert for www.mysite.com
我正在努力解决
- 确保 www 在 URL 中,并且 URL 是 HTTPS
这是我目前所拥有的:
class ApplicationController < ActionController::Base
before_filter :check_uri
def check_uri
redirect_to request.protocol + "www." + request.host_with_port + request.request_uri if !/^www/.match(request.host) if Rails.env == 'production'
end
但这似乎不起作用.任何建议或可能不同的方法来解决以确保 HTTPs 和 www.在网址中吗?
But this doesn't seem to being working. Any suggestions or maybe different approaches to solve for ensuring HTTPs and www. is in the URL?
谢谢
推荐答案
对于 SSL,使用 rack-ssl.
For the SSL, use rack-ssl.
# config/environments/production.rb
MyApp::Application.configure do
require 'rack/ssl'
config.middleware.use Rack::SSL
# the rest of the production config....
end
对于 WWW,创建您自己的机架中间件.
For the WWW, create a Rack middleware of your own.
# lib/rack/www.rb
class Rack::Www
def initialize(app)
@app = app
end
def call(env)
if env['SERVER_NAME'] =~ /^www\./
@app.call(env)
else
[ 307, { 'Location' => 'https://www.my-domain-name.com/' }, '' ]
end
end
end
# config/environments/production.rb
MyApp::Application.configure do
config.middleware.use Rack::Www
# the rest of the production config....
end
要在浏览器中进行测试,您可以在本地开发计算机上编辑 /etc/hosts
文件
To test this in the browser, you can edit your /etc/hosts
file on your local development computer
# /etc/hosts
# ...
127.0.0.1 my-domain-name.com
127.0.0.1 www.my-domain-name.com
在本地开发计算机上以生产模式运行应用程序
run the application in production mode on your local development computer
$ RAILS_ENV=production rails s -p 80
然后浏览到 http://my-domain-name.com/
看看会发生什么.
and browse to http://my-domain-name.com/
and see what happens.
在测试期间,您可能需要注释掉将您重定向到 HTTPS 站点的行.
For the duration of the test, you may want to comment out the line redirecting you to the HTTPS site.
也可以使用许多 Rails 项目使用的标准单元测试和集成测试工具来测试这一点,例如 Test::Unit
和 RSpec
.
There may also be ways to test this with the standard unit-testing and integration-testing tools that many Rails projects use, such as Test::Unit
and RSpec
.
这篇关于Rails - 确保 www 在 URL 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!