3

I wanna make nginx.conf that: - on post proxy_pass on different port - on get returns static files with index.html (serves SPA)

How do I make that, currently I have:

nginx.conf:

worker_processes 1;

events {

    worker_connections 1024;
}

http {

    include mime.types;
    error_log /var/log/nginx/error.log debug;
    default_type application/octet-stream;

    sendfile on;

    keepalive_timeout 65;

    upstream nodejs {

        server 127.0.0.1:3001;
    }


    server {

        listen 3000;

        charset utf-8;
        client_max_body_size 5M;

        location / {

            if ($request_method = POST ) {

                proxy_pass http://nodejs;
            }

            if ($request_method = GET ) {

                root /usr/src/app;
                try_files $uri /index.html;
            }
        }

    }

}

nginx: [emerg] "try_files" directive is not allowed here in /etc/nginx/nginx.conf:41

deathangel908
  • 173
  • 1
  • 2
  • 8
  • You probably don't need both `if` blocks - just remove the second `if` block and place the `root` and `try_files` statements in `location` context. – Richard Smith Oct 11 '18 at 12:39

1 Answers1

3

To quote nginx HTTP server, fourth edition (Packt publishing):

You might wonder: What are the advantages of using a location block over an if block? (...) [T]he main difference lies within the directives that can be employed within either block. Some can be inserted in an if block, and some can't; on the contrary, almost all directives are authorized within a location block.

So I'm afraid try_files is one of those directives that is allowed in a location block but not in an if block.

As for how to work around this problem and do what you want to do, I don't (yet) have an answer for that.

Tommiie
  • 5,627
  • 2
  • 12
  • 46
  • 2
    Can I use [this](https://serverfault.com/a/823053/304770) answer? I didn't find a way to eject try_files into upstream. – deathangel908 Oct 11 '18 at 12:02
  • Wow! That answer used some creative thinking to solve the problem! Thanks for sharing that, @deathangel908! – Tommiie Oct 11 '18 at 12:04