【问题标题】:Serve Rails API and Ionic mobile website together一起服务 Rails API 和 Ionic 移动网站
【发布时间】:2016-07-04 14:36:06
【问题描述】:
基于How to run Ionic serve permanently? 和Deploy Ionic as a website,nginx 应该能够提供来自 Ionic 的 www 文件夹的代码。我正在利用使用相同域地址将其与 Rails 后端一起提供服务的想法......这样就不会增加 CORS 流量和开销。 Rails WEB 的另一个要求是仍然处理网站的桌面 (HTML) 版本。本质上,将有 3 种类型的请求到达 nginx 服务器:
- 从mobile/www/目录加载html、js、css文件
- 移动网站和 APP JSON 调用 Rails API
- 桌面网站对 Rails 的 HTML 调用
类型 2 请求可能很简单,因为它们都具有 .json 扩展名。子域由用户名获取,即 username.example.com,关于如何让 nginx 正确路由 html、js 和 css 请求的任何想法?或者这是一个太大的挑战?
【问题讨论】:
标签:
ruby-on-rails
nginx
ionic-framework
【解决方案1】:
Take #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 :)。