【问题标题】:Multiple subdomains keep redirecting to root path多个子域不断重定向到根路径
【发布时间】:2017-01-20 10:19:48
【问题描述】:

我有一个 Rails 应用程序在 Digital Ocean 上运行 Unicorn,NGINX 在 Ubuntu 上,我正在尝试处理一堆子域,例如 app1.example.com、app2.example.com 等。

在我的路线中,我正在这样做:

constraints(Subdomain) do
  match '/', to: 'pages#landing', via: [:get, :post]
end

这有助于我捕获子域前缀并从控制器显示相应的登录页面。在本地它运行良好,但 NGINX 似乎无论如何都重定向到应用程序的根路径。

这是我的 NGINX 配置:

upstream app_server {
  server unix:/var/run/unicorn.sock fail_timeout=0;
}

server {
  listen 80;
  server_name example.com *.example.com;
  return 301 https://$server_name$request_uri;
}

#When the wildcard above didn't work, 
#I tried hardcoding below but still nothing
server {
  listen 80;
  server_name app1.example.com;
  return 301 https://$server_name$request_uri;
}


server {
  root /home/rails/example/public;
  index index.htm index.html;
  listen 443 ssl spdy;
  listen [::]:443 ssl spdy;
  ...
  ssl_protocols TLSv1.1 TLSv1.2;
  # ssl_ciphers
  ssl_prefer_server_ciphers on;
  add_header Strict-Transport-Security max-age=15768000;
  ssl_stapling on;
  ...
  resolver 8.8.8.8 8.8.4.4 valid=86400;
  resolver_timeout 10;

  location / {
    try_files $uri/index.html $uri.html $uri @app;
  }

  location ~* ^.+\.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|flv|mpeg|avi)$ {
    try_files $uri @app;
  }

  location @app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server;
  }
}

我在这里错过了什么?

【问题讨论】:

    标签: ruby-on-rails nginx


    【解决方案1】:

    我认为您应该使用 $host 变量而不是 $server_name,因为 $server_name 可以只是主机名列表中的第一个值,并且您希望使用用户在 http 标头中指定的主机名。

    server {
      listen 80;
      server_name example.com *.example.com;
      return 301 https://$host$request_uri;
    }
    

    此外,如果您的硬编码示例位于通配符服务器块之后,则它永远不会被匹配,因为请求将始终与它之前的请求匹配,这可能就是为什么这不起作用。

    Related Question

    【讨论】:

    • 这似乎对我有用!现在进入ssl;谢谢!!
    【解决方案2】:
    server {
      listen 80;
      server_name example.com;
    }
    

    以上应该就是您所需要的。您不需要重定向来接受子域,也不需要使用通配符。并去掉“return”

    【讨论】:

      【解决方案3】:

      如果有人遇到所有子域路由都重定向到根路径的问题(在 localhost 和生产环境中),请检查您的子域是否在 routes.rb 中的根域之前定义。否则,他们将始终重定向到着陆页。

      ✅正确示例routes.rb

      # all subdomains go first
      get '/', to: 'pages#status', constraints: { subdomain: 'status' }
      
      # home (landing page)
      root to: 'pages#landing', as: 'landing'
      

      ❌ 这行不通! routes.rb

      # landing page
      root to: 'pages#landing', as: 'landing'
      
      # subdomains => will be redirected to landing page...
      get '/', to: 'pages#status', constraints: { subdomain: 'status' }
      

      【讨论】:

        猜你喜欢
        • 2016-04-03
        • 2016-07-30
        • 2018-10-22
        • 1970-01-01
        • 1970-01-01
        • 2018-10-26
        • 2020-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多