How can I host my API and web app on the same domain?

旧街凉风 提交于 2019-12-21 20:01:18

问题


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/

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


回答1:


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 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;
    }
}

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.

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




回答2:


While Svens answer is completely correct for the question given. I'd prefer doing it at the DNS level so that I can change the server to a new location just in case my API or Web App experience heavy load. This helps us to run our APIs without affecting WebApp and vice-versa

DNS Structure

api.mysite.com => 9.9.9.9
mysite.com = > 9.9.9.9

Since now you'd want both your WebApp and API to run on the same server, you can use nginx to forward requests appropriately.

server {
    listen       80;
    server_name api.mysite.com;
    # ..
    # Removed for simplicity
    # ..
    location / {
        proxy_pass http://localhost:3000;
    }
}
server {
    listen      80;
    server_name www.mysite.com;
    # ..
    # Removed for simplicity
    # ..
    location / {
        proxy_pass http://localhost:8000;
    }
}

Any time in future if you are experiencing overwhelming traffic, you can just alter the DNS to point to a new server and you'd be good.



来源:https://stackoverflow.com/questions/37647459/how-can-i-host-my-api-and-web-app-on-the-same-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!