Search code examples
angularjsnginxstatic-filescloud-foundry

Nginx.conf for angularjs application deployed on Pivotal Cloud Foundry


I have an AngularJs application (v.1.5.7) which has definite routes like www.green.com/ , www.green.com/landing , www.green.com/home , etc,... I'm trying to deploy the angularjs application in PCF using Staticfile_buildpack. I have a custom Staticfile with contents as "root : application". I have my index.html, app.js and other angularjs controllers inside the "application" directory.

My angularJs config has the below routing config,

$routeProvider
.when("/landing", {
        templateUrl: "landing/landing.html",
        controller: 'LandingController'
    })

With the default nginx configuration, my base url (www.green.com/) & other internal routes (eg. /landing through ng-route & $location.path) were served properly. But when i refresh the landing page (www.green.com/landing) it gives me a 404 Not Found error. I understand that nginx is trying to find the directory named "landing" here.

In case of page refresh, I tried to redirect the request back to my base url through custom nginx.conf, so that my index.html will be loaded. My present nginx.conf looks like below,

http{
    server { 
        listen <%=ENV["PORT"] %>;

        index index.html;

        location /landing {
            rewrite ^ http://$host? permanent;
        }

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

When i tried to load my site, I'm getting a 500 Internal Server error & the below error lines in PCF logs.

[error] 54#0: *2 rewrite or internal redirection cycle while internally redirecting to "/index.html",

However when i tried to load www.green.com/landing it is redirecting successfully to my base url and then giving me a 500 Internal Server error.

I tried the following nginx.conf

http{
    server { 
        listen <%=ENV["PORT"] %>;

        index /application/index.html;

        rewrite "^/landing" /application/index.html last;
    }   
}

But I got 404 Not Found error, with the below error in PCF logs,

[error] 49#0: *3 open() "/home/vcap/app/nginx/html/application/index.html" failed (2: No such file or directory),

Please help me to create a working custom nginx.conf file in this case. Thanks in advance!


Solution

  • If you have enabled html5Mode in your code, you need to set base tag in index file.along with that,

    server {
        server_name my-app;
    
        index index.html;
    
        root /path/to/app;
    
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
    

    This is the Nginx Rewrites for angular site.