📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.


title: "Nginx Config for Nodejs app" lang: "js" date: "2024-03-24T14:44:54.393Z" published: true

Simple nginx configuration using the domain api.ahmadrosid.com to proxy requests to a Node.js app running on localhost:3000:

server {
    listen 80;
    server_name api.ahmadrosid.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Explanation:

  • listen 80;: Listens for incoming HTTP requests on port 80.
  • server_name api.ahmadrosid.com;: Sets the server name to api.ahmadrosid.com.
  • location / {...}: This block handles requests for the root (/) location.
  • proxy_pass http://localhost:3000;: Proxies the request to http://localhost:3000 where your Node.js app is running.
  • proxy_http_version 1.1;: Enables HTTP/1.1 proxying.
  • proxy_set_header Upgrade $http_upgrade;: Upgrades the proxied connection to WebSocket if the client requested it (useful for real-time communication in Node.js apps).
  • proxy_set_header Connection 'upgrade';: Upgrades the proxied connection to WebSocket if the client requested it.
  • proxy_set_header Host $host;: Sets the Host header to the host requested by the client.
  • proxy_cache_bypass $http_upgrade;: Bypasses the proxy cache if the client requested a WebSocket upgrade.

Make sure that your Node.js app is running on localhost:3000.

After configuring nginx, you may need to restart the nginx service for the changes to take effect.

Run this command if you are using debian or ubuntu.

sudo systemctl restart nginx