The NGINX reverse proxy fails to forward requests to an Express application

I am currently in the process of setting up a dedicated API backend for a website that operates on /mypath, but I am encountering issues with NGINX not properly proxying requests.

Below is the nginx configuration located within the sites-enabled directory:

upstream backend_website {
        server 127.0.0.1:5173;
}

upstream backend_api {
        server 127.0.0.1:5001;
}


# HTTP
#
server {
       listen 80;
       listen [::]:80;

       server_name example.com;

       # Redirect to HTTPS (:443)
       return 301 https://$host$request_uri;
}

# HTTPS
#
server {
        listen 443 ssl;
        listen [::]:443 ssl;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        server_name example.com;

        location / {
                include proxy_params;
                proxy_pass https://backend_website;
        }

        location /mypath {
                include proxy_params;
                proxy_pass https://backend_api;
        }
}

The code snippet from the index.ts file for the service is displayed below:

import cors from "cors";
import express from "express";
import { config } from "config";
import { MyController } from "controllers/my.controller";
import * as https from "https";
import * as fs from "fs";

const certificate = fs.readFileSync("/etc/letsencrypt/live/example.com/fullchain.pem", "utf8");
const privateKey = fs.readFileSync("/etc/letsencrypt/live/example.com/privkey.pem", "utf8");

const app = express();
app.use(express.json());
app.use(cors());
app.use("/", MyController );

const httpsServer = https.createServer({
    cert: certificate,
    key: privateKey
}, app);

httpsServer.listen(config.PORT, "127.0.0.1", () => console.log(`Running api on https://127.0.0.1:${ config.PORT }/`));

Despite the setup, the server fails to correctly proxy requests to the API when accessed through the designated /mypath. While the root path (utilizing Vite) functions smoothly, attempting to access /mypath results in a Cannot GET /mypath error. Checking via lynx.browser.org reveals that 127.0.0.1:5001 does indeed work, indicating an issue somewhere within the NGINX configuration.

Answer №1

You must make changes to the /etc/nginx/site-enabled/ configuration file.


 cd /etc/nginx/site-enabled/
 sudo nano default

    location /wishfoundationindia/ {
                proxy_pass http://localhost:8000/;
                proxy_buffering off;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-Host $host;
                proxy_set_header X-Forwarded-Port $server_port;
        }

        location /lms/ {
                proxy_pass http://localhost:7000/;
                proxy_buffering off;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-Host $host;
                proxy_set_header X-Forwarded-Port $server_port;
        }

Afterward, adjust the settings within the location function referring to this visual aid. rfr image

Answer №2

I came across the solution. It may seem counterintuitive, but you need to explicitly specify that Express should serve on /mypath/, even if it's already configured in the NGINX file.

Here is the original code snippet:

const app = express();
app.use(express.json());
app.use(cors());
app.use("/", MyController );

const httpsServer = https.createServer({
    cert: certificate,
    key: privateKey
}, app);

httpsServer.listen(config.PORT, "127.0.0.1", () => console.log(`Running api on https://127.0.0.1:${ config.PORT }/`));

Now, after making the necessary adjustment:

const app = express();
app.use(express.json());
app.use(cors());
app.use("/mypath", MyController );

const httpsServer = https.createServer({
    cert: certificate,
    key: privateKey
}, app);

httpsServer.listen(config.PORT, "127.0.0.1", () => console.log(`Running api on https://127.0.0.1:${ config.PORT }/`));

Answer №3

Update your nginx configuration with the following:

location  /newpath {
      rewrite /bar/(.*) /$1  break;
      proxy_pass         https://backend_server;
      proxy_set_header   Host $host;
}

After making this change, access http://example.com/newpath/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Best practices for updating nested properties in Angular objects

I have a dataset that includes information about fruit prices for different years: { "fruits": [ { "name": "apple", "prices": [ { "2015": 2, "2014": 3, ...

What is the best way to make a box modal function that displays a different image source than the one shown in the modal?

I'm looking to create a box modal that shows one image on the page, and then displays a different image in the popup when clicked. Here's what I currently have: <div class="row"> <div class="modal-image"><img id="myImg" src="http ...

Component failing to refresh with each key modification

My understanding is that adding a key attribute to a component should make it reactive when the key changes. However, with a v-navigation-drawer from Vuetify, this doesn't seem to have any impact. I've tried making arbitrary changes to the logge ...

Tips for enhancing query speed in mongodb

I have a huge MongoDB collection with over 5 million documents. Every time I try to add a new document, I need to check if there is already a document with the same title in the collection before inserting it. For example, let's say this is my MongoD ...

"Creating a backend server using Node.js, TypeScript, and g

I am currently in the process of developing a nodejs project that will consist of 3 key services: Gateway Product Order The Product and Order services will perform functions related to their respective names, while the Gateway service will take JSON requ ...

The router is displaying the component directly on the current page rather than opening it on a separate page

The issue is that the router is rendering the page on the same page instead of generating a new one. When clicking on the Polls link, it only renders the page there but the URL changes in the browser. Polls.js import React from 'react'; import ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

HeaderView in Angular Framework

When exploring the best practices for organizing an AngularJS structure, I came across the recommendation to implement partial views as directives. Following this advice, I created a directive for my app header. In my specific header design, I included a ...

Can a single endpoint provide various JSON responses depending on the user's role?

I seem to be facing a terminology confusion which may be hindering my ability to find a solution. My current project involves creating a REST API within Express and I intend to incorporate roles in the authorization process. What I am curious about is whet ...

JavaScript: Utilize MooTools to extract a string containing a specific class and then pass it through a parent function

I am facing a major issue and struggling to find a solution for it. My problem involves returning values, mostly strings, that I can utilize in various contexts. For instance, I need to verify whether something is 0 or 1 in an if/else statement, or insert ...

How does the functionality of $.ajax differ from that of $.get?

Similar Inquiry: Understanding the Variations of $.ajax(), $.get(), and $.load() I'm curious about the disparities between $.get() and $.ajax The given code showcases calls like this: $.get(href) .success(function (content) { $(&apos ...

Simple and quickest method for incorporating jQuery into Angular 2/4

Effective ways to combine jQuery and Angular? Simple steps for integrating jQuery in Angular2 TypeScript apps? Not sure if this approach is secure, but it can definitely be beneficial. Quite intriguing. ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

The console is displaying a null value outside of the block, however, the correct value is returned when

I am having an issue where the first console.log() is not returning the correct value, but the second one is. Can anyone provide assistance with this problem? angular.module('resultsApp', ['ngCookies']) .config(['$qProvider&a ...

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

Exploring the power of real-time queries with Stubby4node

I'm attempting to achieve the following: # Finding Destination by ID - request: .... query: serviceId: "s009" response: file: destinations/destination-by-service-id-$serviceId.json ... My goal is for the serviceId to correspond with ...

Changing global properties in VueCli

Recently, I integrated a component library into my Vue 3 project. All instances of the component require the same styles. Instead of manually adjusting each instance's props, I opted to utilize a global property: app.config.globalProperties.$tooltipS ...

The error message "window is not defined" is commonly encountered in Next

Having some trouble with using apexcharts in a next.js application, as it's giving me an error saying 'window is not defined'. If anyone has any insights or solutions, I would greatly appreciate the help. Any ideas on what could be causing ...

Is it possible to ensure only one value is set as true in useReducer without manually setting the rest to false

I am seeking a more efficient method to ensure that only one value is set to true while setting the rest to false I came across this Python question and answer recommending an enum (I am not very familiar with that concept) Currently, I have the followin ...