如何在同一个域中托管我的 API 和 Web 应用程序?

如何在同一个域中托管我的 API 和 Web 应用程序?

问题描述:

我有一个 Rails API 和一个 Web 应用程序(使用 express),完全独立且彼此独立.我想知道的是,我是否必须单独部署它们?如果我这样做,我怎样才能使我的 api 在 mysite.com/api 中,而 web 应用在 mysite.com/

I have a Rails API and a web app(using express), completely separate and independent from each other. What I want to know is, do I have to deploy them separately? If I do, how can I make it so that my api is in mysite.com/api and the web app in mysite.com/

我见过很多这样的项目,甚至将 api 和应用程序放在单独的存储库中.

I've seen many projects that do it that way, even have the api and the app in separate repos.

通常您不会直接向客户端公开此类 Web 应用程序.相反,您使用代理服务器,将所有传入请求转发到节点或 Rails 服务器.

Usually you don't expose such web applications directly to clients. Instead you use a proxy server, that forwards all incoming requests to the node or rails server.

nginx 是一个受欢迎的选择.初学者指南 甚至包含一个与您尝试执行的操作非常相似的示例.

nginx is a popular choice for that. The beginners guide even contains a very similar example to what you're trying to do.

你可以用类似这样的配置来实现你想要的:

You could achieve what you want with a config similar to this:

server {
    location /api/ {
        proxy_pass http://localhost:8000;
    }

    location / {
        proxy_pass http://localhost:3000;
    }
}

这假设您的 API 在本地运行在 8000 端口,您的 Express 应用在 3000 端口上运行.此外,这不是一个完整的配置文件 - 这需要加载或添加到 http 块中.从发行版的默认配置开始.

This is assuming your API runs locally on port 8000 and your express app on port 3000. Also this is not a full configuration file - this needs to be loaded in or added to the http block. Start with the default config of your distro.

当有多个位置条目时,nginx 会选择最具体的一个.您甚至可以添加更多条目,例如提供静态内容.

When there are multiple location entries nginx chooses the most specific one. You could even add further entries, e.g. to serve static content.