一起服务Rails API和Ionic移动网站

时间:2016-03-18 00:44:18

标签: ruby-on-rails nginx ionic-framework

基于How to run Ionic serve permanently?Deploy Ionic as a website,nginx应该能够提供来自Ionic的www文件夹的代码。我正在利用使用相同域地址的Rails后端服务它的想法......这样就不会添加任何CORS流量和开销。 Rails WEB的另一个要求是仍然处理网站的桌面(HTML)版本。从本质上讲,将有3种类型的请求进入nginx服务器:

  1. 从mobile / www /目录
  2. 加载html,js,css文件
  3. 移动网站和APP JSON调用Rails API
  4. 桌面网站HTML调用Rails
  5. 类型2请求可能很简单,因为它们都具有.json扩展名。子域名是用户名,即username.example.com,有关如何让nginx正确路由html,js和css请求的任何想法?或者这是一个太大的挑战?

1 个答案:

答案 0 :(得分:2)

拿#1:想出一个Nginx配置,当Rails以隐藏方式发出信号时,它会返回Ionic文件。可能很笨拙,所以请随时提出批评,陷阱或改进。

Nginx配置:

server {
  # Development logging
  access_log /home/builder/projects/web/log/access.log;
  error_log /home/builder/projects/web/log/error.log notice;

  listen  80;
  server_name projects.host www.projects.host;

  # Eusure Rails' index route gets uri "/" first.
  index index.html;

  # All API json calls and requests to Rails controllers.
  location ~ ^\/(.+\.json$|others.*|users.*|index\.html$) {

    # Rails server
    proxy_pass  http://127.0.0.1:3000;

    # The Rails server may request Ionic mobile website with a temporary redirect (status 307)
    proxy_intercept_errors on;
    error_page 307 = @temp_redirect;
  }

  # If a temporary redirect is to /mobile_web, response with Ionic mobile root.
  location @temp_redirect {
    if ($upstream_http_location ~ ^http.+\/\/.+\/mobile_web$) {
      set $mobile true;
      root /home/builder/projects/mobile/www;
    }
    # Something else, return it.
    if ($mobile != true) {
      return 307 $upstream_http_location;
    }
  }

  # Ionic mobile root
  location / {
    root        /home/builder/projects/mobile/www;
  }
}

在RoR中:

  # Decide whether to handle the root action within Rails app or to
  # signal the downstream server (nginx) to return Ionic mobile web.
  def index
    # TODO: Needs a bit of logic before the following redirect.
    redirect_to '/mobile_web', status: :temporary_redirect  # 307
  end

带有一个APP的两只鸟:)。