Node.js + Nginx - What now?

后端 未结 12 1642
抹茶落季
抹茶落季 2020-11-22 00:26

I\'ve set up Node.js and Nginx on my server. Now I want to use it, but, before I start there are 2 questions:

  1. How should they work together? How should I handl
12条回答
  •  被撕碎了的回忆
    2020-11-22 00:52

    Nginx can act as a reverse proxy server which works just like a project manager. When it gets a request it analyses it and forwards the request to upstream(project members) or handles itself. Nginx has two ways of handling a request based on how its configured.

    • serve the request
    • forward the request to another server

      server{
       server_name mydomain.com sub.mydomain.com;
      
       location /{ 
        proxy_pass http://127.0.0.1:8000;  
        proxy_set_header Host $host;
        proxy_pass_request_headers on;  
       }
      
       location /static/{
         alias /my/static/files/path;
       }
      

      }

    Server the request

    With this configuration, when the request url is mydomain.com/static/myjs.js it returns the myjs.js file in /my/static/files/path folder. When you configure nginx to serve static files, it handles the request itself.

    forward the request to another server

    When the request url is mydomain.com/dothis nginx will forwards the request to http://127.0.0.1:8000. The service which is running on the localhost 8000 port will receive the request and returns the response to nginx and nginx returns the response to the client.

    When you run node.js server on the port 8000 nginx will forward the request to node.js. Write node.js logic and handle the request. That's it you have your nodejs server running behind the nginx server.

    If you wish to run any other services other than nodejs just run another service like Django, flask, php on different ports and config it in nginx.

提交回复
热议问题