AngularJS and API Backend via nginx proxy – Sample nginx virtual host

If you want to run your AngularJS front-end web application and run nginx as your API proxy server, then the following nginx virtual host configuration can help you.


#AngularJS frontend with proxied API backend
server {
        listen 80;
        server_name your-angularjs-public.url;

        root your/angularjs/app/root-directory;
        index index.html;

        location / {
                # If you want to enable html5Mode(true) in your angularjs app for pretty URL
                # then all request for your angularJS app will be through index.html
                try_files $uri /index.html;
        }

        # /api will server your proxied API that is running on same machine different port
        # or another machine. So you can protect your API endpoint not get hit by public directly
        location /api {
                proxy_pass http://api-server-url;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        #Static File Caching. All static files with the following extension will be cached for 1 day
        location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
                expires 1d;
        }
}

This will help you lot to configure your Nginx proxy for your API backend and run your API with AngularJS based web application interface.