多个子域保持重定向到根路径

时间:2016-09-12 22:01:27

标签: ruby-on-rails nginx

我在数字海洋上运行了一个Rails应用程序,在Ubuntu上使用Unicorn,NGINX,我正在尝试处理一堆子域,例如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;
  }
}

我在这里缺少什么?

3 个答案:

答案 0 :(得分:1)

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

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

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

Related Question

答案 1 :(得分:0)

server {
  listen 80;
  server_name example.com;
}

以上就应该是你所需要的。您无需重定向即可接受子域,也无需使用通配符。并删除“返回”

答案 2 :(得分:0)

如果有人遇到所有子域路由都重定向到根路径(在本地主机和生产中)的问题,请检查您的子域是否在 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' }
相关问题