0

I am new to nginx and I am following tutorials to set up nodejs app with nginx reverse proxy but nothing seems to be working. I have a very simple configuration and I’m not sure what the problem is can anybody let me know? I am just trying to get the standard welcome to nginx page to be served at my_domain/ and then proxy to my node app at my_domain/api but the node app doesn’t seem to be working. When I navigate to my_domain/ I get the standard welcome to nginx page, but when I go to my_domain/api I get "cannot GET /api"

The default config file for nginx

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name my_domain;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    location /api {
        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;
    }

    
}

The nodejs app

const app = express()


app.use(express.json())


app.get('/', (req, res) => {
    res.send('<div><h1>Hello world</h1></div>')
})

app.get('/products', (req, res) => {
    res.send('<div><h1>All Products</h1></div>')
})

app.get('/products/:id', (req, res) => {
    const id = req.params.id
    res.send(`<div><h1>Product: ${id}</h1></div>`)
})



const PORT = 3000

app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`)
})
jim
  • 53
  • 5

1 Answers1

0

you need to use proxi_pass on your case. for nginx what you can do is to rewrite the requests for the relevant port, in your case to 3000. this is how i handle it.

    location /node/ {
    rewrite /node/(.*)  /$1 break;
    proxy_pass http://localhost:3000;
}
Dump Eldor
  • 92
  • 1
  • 11