Nginx – How to configure Glassfish + NGINX to serve static files with NGINX

glassfishjavanginxstatic-filesweb-applications

I have a EC2 ubuntu with Glassfish v3 + Nginx setup to host my java web application. This application is deployed as a WAR file to Glassfish . The NGINX is currenty passing all request to the glasshfish appserver including the ones for static images, css etc. javascripts etc.

server {
  listen  80;
  server_name whatever.com www.whatever.com;

  access_log  /var/log/nginx/whatever.com.access.log;

  location / {
    proxy_pass  http://127.0.0.1:8080/javapp/;
    proxy_pass_header Set-Cookie;
    proxy_pass_header X-Forwarded-For;
    proxy_pass_header Host;
  }

}

Best Answer

I have solved this as follows a) Modify the config file as follows

server {

        listen   80; ## listen for ipv4
        server_name  www.whatever.com; ## change this to your own domain name
    root   /home/ubuntu/www/public_html;
## Only requests to our Host are allowed i.e. nixcraft.in, images.nixcraft.in and www.nixcraft.in
      if ($host !~ ^(www.whatever.com)$ ) {
         return 444;
      }


    location ~* \.(jpg|jpeg|gif|css|png|js|ico)$ {
        access_log off;
        expires max;
    }

    location / {
        access_log off;
        proxy_pass http://localhost:8080;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                root   /var/www/nginx-default;
        }


}

b) under the Nginx HTML root (/home/ubuntu/www/public_html)create a subdir with the same name as the context of your web appplication. e.g. if your webpp url is www.whatever.com/mycoolapp, create a directory called /home/ubuntu/www/public_html/mycoolapp

c) unzip the war file to this folder. Get rid of the WEB-INF folder

d) restart nginx . To verify, stop your web application while keeping NGINX up and access a an image or css from your webapp.