malcoauri
malcoauri

Reputation: 12189

nginx redirect all requests except api to one file

There is the following nginx config:

server {
  listen 80;
  server_name orange.mwlab.co;
  root /home/hotels-app/domains/orange_web_app;
  location /api {
    passenger_enabled on;
    rails_env stage;
    root /home/hotels-app/domains/orange_app/current/public;
  }

  location / {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
  }
}

I want to do the following thing: all requests except requests from API (/api/...) redirect to /home/hotels-app/domains/orange_web_app, because I made a single page application and I need to return a static index.html except API requests. Thanks in advance!

Upvotes: 3

Views: 1577

Answers (1)

sunaurus
sunaurus

Reputation: 64

You can use try_files.

server {
  listen 80;
  server_name orange.mwlab.co;
  root /home/hotels-app/domains/orange_web_app;
  location /api {
    passenger_enabled on;
    rails_env stage;
    root /home/hotels-app/domains/orange_app/current/public;
  }

  location / {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
    try_files $uri $uri/ /index.html =404;
  }
}

Make sure to use the correct path for index.html.

The string try_files $uri $uri/ /index.html =404; means that now all non-existent url will be forwarded to index.html file, but without rewriting url in the browser address bar.

Here is a blog post with more info (it's written about angularjs but most of it applies to any single page app): http://senior-java-developer.com/html5angularjsnginx-crawlable-application/

Upvotes: 3

Related Questions