Growing Dev
Growing Dev

Reputation: 49

Nginx redirect to Node.js backend

I want to redirect a URL e.g domain.com/api/ to a specific Node.js server, the root URL shows my website. At the moment I use this config:

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

        root /var/www/html;

        server_name _;

        location / {

                try_files $uri $uri/ =404;
        }

        location /api {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_pass http://localhost:3031/;
            proxy_ssl_session_reuse off;
            proxy_set_header Host $http_host;
            proxy_cache_bypass $http_upgrade;
            proxy_redirect off;
}

but it does not work.

What has gone wrong?

Thanks for help and best regards :)

Upvotes: 2

Views: 3648

Answers (2)

JohnnyJS
JohnnyJS

Reputation: 1472

Please note that proxy_pass directive gets argument for backend and optional URI.

That means proxy_pass http://localhost:3031; will get the URI from the user, e.g /api/res.json so final URL for the NODE JS is: http://localhost:3031/api/res.json

But when you provide the URI to the directive itself, it overrides the requested URI in the matching location. e.g location /api and proxy_pass http://localhost:3031/; (note the suffixed slash). so the part /api is replaced by / and final URL is: http://localhost:3031/res.json.

from the NGINX docs:

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:

location /name/ {
  proxy_pass http://127.0.0.1/remote/;
}

So it's important to understand that the part of the requested URI /name/ is replaced by /remote/ and then the rest of the requested URI is added to the final sent URI.

Upvotes: 0

Aleksey Druzhinin
Aleksey Druzhinin

Reputation: 96

You fogot closing bracket after location /api section. Your config working at my machine.

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

    root /var/www/html;

    server_name _;

    location / {

            try_files $uri $uri/ =404;
    }

    location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:3031/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
     }
  }

Also your nodejs backend must handle '/api' requests.

Upvotes: 2

Related Questions