yathirigan
yathirigan

Reputation: 6059

How to do URL rewrite for all URLs except a specific URL using Nginx?

I have deployed my web application in Nginx 1.8 and also using Nginx for a reverse proxy configuration.

I want the following to happen. I am able to achieve 1 & 2. How can i get the 5 implemented in an Nginx configuration ? 3 & 4 are sample scenarios of scenario 5

  1. URL http://localhost in browser --> Have to display index.html
  2. URL http://localhost/app --> Have to proxy_pass to http://localhost:8081
  3. URL http://localhost/login --> Have to display index.html as http://localhost
  4. URL http://localhost/dashboard --> Have to display index.html as http://localhost
  5. URL http://localhost/Anything_Other_than_app --> Have to display index.html as http://localhost

my problem is, this index.html has a Login functionality, on successful, login it redirects user to a URL http://localhost/dashboard and displays list of users. If any user name is clicked, it redirets to http://localhost/user to display their details.

UseCase: Now if i directly type the http://localhost/dashboard or http://localhost/user URL, Nginx is searching for this folder and a index page under my root and giving 404 error. Instead, what i want is to display the Index.html page, which has the logic to display the list of users or the login page based on the session exists or not.

Solution We Used:

location = /index.html {
         root   myTestApp;
        }
        location ~* .*\.png$ {
         root   myTestApp;
        }
        location ~* .*\.jpg$ {
         root   myTestApp;        
        }
        location ~* .*\.css$ {
         root   myTestApp;        
        }
        location ~* .*\.gif$ {
         root   myTestApp;        
        }
        location ~* .*\.js$ {
         root   myTestApp;
        }   

        location / {
            root   myTestApp;
            rewrite ^(.*)$ /index.html;          
        }  

      location /app {
            proxy_pass http://localhost:8081;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;              

        }  

Upvotes: 0

Views: 623

Answers (1)

Alexey Ten
Alexey Ten

Reputation: 14354

Easy

location / {
    try_files /index.html =404;
}

location /app/ {
    # proxy to your app
}

Upvotes: 1

Related Questions