如何让 NGINX 提供像 .js、.css、.html 这样的静态内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23776660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to make NGINX serve static content like .js, .css, .html?
提问by Pulkit
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
最近我开始使用 NGINX,我发现我们可以将它用于反向代理,从自身提供静态内容,可以减少加载时间。我在我的本地机器上有一个 Tomcat/JBoss 服务器,我想把 NGINX 放在它前面,这样静态内容将从 NGINX 提供,并由 Tomcat/JBoss 所有。我的 Tomcat/JBoss 应用程序在http://localhost:8081/Test
我的 NGINX 配置上运行正常,但无法加载css/js/jpg
文件。这是我的War结构,静态内容是
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)
我认为问题是由于绝对路径,所以我应该复制资源文件夹并将其放在NGINX中的某个文件夹中并配置我的NGINX从其自己的目录中选择文件而不是去Tomcat / JBoss吗?我是新手,所以我不知道这样做任何人都可以帮助我。这是我的 NGINX(windows) conf 文件
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/;
}
回答by ist
You can add locationwith 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/;
}
}
回答by cyber8200
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
在您的 CLI 中运行 ab -c 20 -n 1000 https://your-site/any-file
You will see Time taken for testsdecrease drastically.
您会看到测试所用的时间急剧减少。