Nginx学习:使用nginx配置静态资源(js或者image)并访问后台的数据(使用vue中的ajax)
1.简介由于今天学习了ngnix,并了解了其中的属性决定配置一个静态资源服务器,用于获取js以及访问后台的数据2.当前nginx的配置conf#usernobody;worker_processes1;error_loglogs/error.log;#pidlogs/nginx.pid;events {worker_connections...
1.简介
由于今天学习了ngnix,并了解了其中的属性决定配置一个静态资源服务器,用于获取js以及访问后台的数据
2.当前nginx的配置conf
#user nobody;
worker_processes 1;
error_log logs/error.log;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#开启gzip
gzip on;
server {
listen 8000;
server_name localhost;
charset utf-8;
#配置当前的图片
location ~ \.(gif|jpg|jpeg)$ {
root static;
}
#配置当前所有以js和css结尾的数据都调用neginx的static文件夹中的内容
location ~ \.(js|css)$ {
root static;
}
#将访问SpringBoot的请求转发到8080端口的SpringBoot
location / {
proxy_pass http://127.0.0.1:8080/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
这就是我的配置:其中在当前的nginx中添加一个static文件夹,其中js中的内容为:
location / {
proxy_pass http://127.0.0.1:8080/;
},这句话表示当前所有的访问都会映射到当前的8080端口去
例如:访问localhost:8000/index就会访问到http://127.0.0.1:8080/index中去
,注意这里的格式问题,proxy_pass中需要在最后面加上/
3.编写SpringBoot项目
当前的pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 导入测试模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
项目结构:
当前的项目内容借鉴我的:vue之ajax访问后台(axios)
4.启动项目并开始访问
访问:http://localhost:8000/index的显示结果
发现当前的js全部都被nginx拦截并返回了!
执行vue的ajax访问后台
后台结果:
5.总结
1.使用nginx作为静态资源服务器的时候需要注意当前的路径匹配的问题
,一旦路径不匹配就会出现404错误,还需要注意location的编写问题
!
2.通过当前的nginx访问
就会转发到指定的proxy_pass这个路径
,前提是路径必须匹配,否者首页无法访问
3.通过nginx返回js的时候需要使用正则表达式
来处理相对应的匹配问题!
以上纯属个人见解,如有问题请联系本人!
更多推荐
所有评论(0)