【问题标题】:Make rails url_helpers use https in production让 rails url_helpers 在生产中使用 https
【发布时间】:2015-04-10 01:42:59
【问题描述】:

我使用 Rails url_helpers 在我的应用程序中构建资源 url。 开发中的 url 示例是 http://localhost:3000/resource/1,由 resource_url(resource) url_helper 生成。

我在生产环境中使用 nginx proxy_pass 将请求发送到我的 rails 应用程序。我的 nginx 在端口 433 https 上侦听并重定向到我在端口 5000 http 上的 rails 应用程序:

server {
  listen 443 ssl;
  server_name     api.staging.zup.me;

  ssl_certificate /etc/ssl/certs/cert.crt;
  ssl_certificate_key /etc/ssl/certs/cert.key;

  location / {
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass      http://localhost:5000;
  }
}

因为我的 Rails 应用程序从 nginx 代理收到的请求是 http,它会生成像 http://example.com/resource/1 这样的 url,但只有在生产中我希望我的所有 url 都使用 https,例如https://example.com/resource/1

让 Rails 仅在生产环境中使用 https 协议生成 url 的最佳方法是什么?

【问题讨论】:

标签: ruby-on-rails nginx


【解决方案1】:

您可以在 nginx 中使用重定向,并且永远不要触摸 rails 应用程序来启用 https:

server {
  listen 80 default_server deferred;
  server_name myserver.domain;

  return 301 https://$server_name$request_uri;  # enforce https
}

# HTTPS server
server {
  listen 443;
  server_name myserver.domain;
  ssl on;
  ssl_certificate /etc/nginx/ssl/myserver.domain.crt;
  ssl_certificate_key /etc/nginx/ssl/myserver.domain.key;

  root /srv/www/myserver;
  ...
}

不确定这是否是最好的方法,但我喜欢它,因为您不必对 rails 应用程序做任何事情,只需 nginx。

【讨论】:

  • 我的问题不是ssl配置,而是Rails url生成。我编辑了问题以使其更清楚。
猜你喜欢
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 2015-02-22
  • 2012-03-13
  • 1970-01-01
  • 2017-11-08
相关资源
最近更新 更多