how to make NGINX serve static content like .js, .

2019-03-25 03:47发布

问题:

Recently I have started using NGINX, I found that we can use it for reverse proxy, serving static content from itself which can reduce load time. I have a Tomcat/JBoss server on my local machine and I want to put NGINX in front of it so that static content will be served from NGINX and rest all by Tomcat/JBoss. My Tomcat/JBoss application is running on http://localhost:8081/Test my NGINX configuration worked properly but it is not able to load css/js/jpg file. Here is my war strcuture wehere static contents are

Test.war

TEST
  |
  |--->Resources
  |       |------->CSS
  |       |         |----> style.css
  |       |
  |       |-------->Images
  |                  |----> a.jpg
  |                  |----> b.jpg
  |   
  |--->WEB-INF
  |        |----->Web.xml
  |        |----->spring-servlet.xml
  |
  |--->JSP
         |---->login.jsp

I think the problem is because of absolute path, so should I copy resources folder and put it in some folder in NGINX and configure my NGINX to pick file from its own directory rather going to Tomcat/JBoss? I am new so I dont have any idea of doing this can anyone pls help me in this. This is my conf file for NGINX(windows)

server {
        listen 80;
        server_name localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
             proxy_pass http://127.0.0.1:8081/Test/;
        }

回答1:

You can add location with regexp:

server {
    listen 80;
    server_name localhost;

    location ~* \.(js|jpg|png|css)$ {
        root path/to/tomcat/document/root/Test/;
        expires 30d;
    }

    location / {
        proxy_pass http://127.0.0.1:8081/Test/;
    }
}


回答2:

Try

server {
    listen 80;
    server_name localhost;

    location ~* \.(css|js|gif|jpe?g|png)$ {
        expires 168h;
    }

    location / {
        proxy_pass http://127.0.0.1:8081/Test/;
    }
}

How to test

In your CLI run ab -c 20 -n 1000 https://your-site/any-file

You will see Time taken for tests decrease drastically.