K Johnson
K Johnson

Reputation: 488

Nginx SPA Serving Static Files, Proxying API Calls, and Rewriting to /index.html

So, I'd like to have an nginx.conf that...

  1. Serves all /static requests directly
  2. Proxies all /api requests to another local server (port 8200)
  3. Serves /index.html for all other requests (so, /contact/123 would really serve /index.html)

Here is my current config...

server {
listen                      80;
server_name                 www.xyz.io;
root                        /opt/xyz/www;

location / {
    try_files $uri $uri/ @backend;
}

location @backend {
    proxy_pass http://127.0.0.1:8200;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
}

}

I'm really not clear how to have all other requests serve /index.html though. Ideas?

Upvotes: 3

Views: 4654

Answers (1)

hd.deman
hd.deman

Reputation: 1306

Try this:

server {

   listen                      80;
   server_name                 www.xyz.io;
   root                        /opt/xyz/www;

   # index
   index index.html;

   # $uri, index.html
   location / {
     try_files $uri $uri/ /index.html;
   }

   location /api {
     proxy_pass http://127.0.0.1:8200;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "Upgrade";
   }

}

Upvotes: 6

Related Questions