ruby-on-rails - 如何使用 nginx 设置从 http 到 https 的重定向?

标签 ruby-on-rails ruby http nginx https

我整天都在为这个问题而战。 这是我的 nginx.cong:

upstream my_website.co {
      server 127.0.0.1:8080;
    }

    server{
      listen 80;
      listen  443 default ssl;
      # return 301 https://www.my_website.co; - I put it here, but it didn't work  

      ssl on;
      ssl_certificate      /etc/nginx/certs/my_website.co.crt;
      ssl_certificate_key  /etc/nginx/certs/my_website.co.private.key;

      server_name my_website.co _;

      root /home/deployer/my_website/public;

      location / {
        proxy_set_header X_FORWARDED_PROTO $scheme;
        proxy_set_header Host $http_host;
        proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   Host              $http_host;
        proxy_set_header   X-Real-IP         $remote_addr;
        proxy_set_header   CLIENT_IP         $remote_addr;

        if (!-f $request_filename) {
          proxy_pass http://my_website.co;
          break;
        }
        if (-f $document_root/system/maintenance.html) {
          return 503;
        }
      }
      # return 301 https://www.my_website.co; - I put it here, but it didn't work  

请问如何将所有内容从 http 重定向到 https

我的 Rails 代码:

应用程序 Controller

before_filter :ensure_domain
APP_DOMAIN = 'www.my_website.co'
  def ensure_domain
    if request.env['HTTP_HOST'] != APP_DOMAIN && Rails.env != 'development'
      redirect_to "https://#{APP_DOMAIN}#{request.env['REQUEST_PATH']}", :status => 301
    end
  end

我会很感激你的帮助,我在这里迷路了。

谢谢

最佳答案

我在我的一个站点的 nginx 配置文件中做了类似的事情,它没有问题。我的 ApplicationController 中也没有任何内容来强制重定向。

server {
            listen 80;
            server_name my_website.co;
            rewrite ^ https://server_name$request_uri? permanent;
    }

server {
            listen 80;
            server_name www.my_website.co;
            rewrite ^ https://server_name$request_uri? permanent;
    }

server {
            listen       443;
            server_name  my_website.co;
            root /home/deployer/my_website/public;

            ssl on;
            ssl_certificate      /etc/nginx/certs/my_website.co.crt;
            ssl_certificate_key  /etc/nginx/certs/my_website.co.private.key;

            // rest of your config file below
    }

关于ruby-on-rails - 如何使用 nginx 设置从 http 到 https 的重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21469220/

相关文章:

ruby-on-rails - 使用 Devise/Rails 4/Minitest 运行 Controller 测试时无法登录

ruby-on-rails - Pundit::NotAuthorizedError/pundit 授权问题

ios - 'state changing' APNS 失败时的应用架构

ruby - 旋转一组物体坐标

php - Laravel 多对多查询 Controller

android - "org.apache.http.client.NonRepeatableRequestException"安卓上传图片时

ruby-on-rails - Rails 5 使用 :id 向 REST 路由添加自定义操作

ruby-on-rails - rails : Best practice to store user settings?

ruby-on-rails - 如何在 Rails 环境中的 RubyMine 或 IDEA 中运行 scratch 文件?

ruby - 从原始范围之外的 ruby block 返回