David
David

Reputation: 373

NGINX Serve all static files and forward others to proxy without / giving 403?

I'm trying to configure an nginx server to act as a proxy to a node application. What I would like is to have any static files served by nginx and all other paths forwarded on to the Node.js application (inluding the / path).

I've seen the following question/answers: How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

And as directed, I've configured my site config as follows:

server {
  server_name subdom.domain.com;
  listen 80;
  location / {
    root /var/www/application/public_html;
    try_files $uri $uri/ @application;
  }
  location @application {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://localhost:3000;
  }
}

However when browsing to subdom.domain.com/ I get a 403 Forbidden. I'm guessing this is because nginx cannot find a default document, but I want the default document to be send to proxy, any idea how to do this?

Upvotes: 0

Views: 1346

Answers (1)

michelem
michelem

Reputation: 14590

This should do the work:

  server {
    server_name subdom.domain.com;
    listen 80;

    location / {
        try_files $uri;

        proxy_set_header X - Real - IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X - Forwarded - For $proxy_add_x_forwarded_for;
        proxy_pass http: //localhost:3000;

    }
  }

Brief explanation for each URL it finds a file it will serve that (try_file), for everything else it tries the proxy

Upvotes: 2

Related Questions