Nginx学习:使用nginx配置静态资源(js或者image)并访问后台的数据(使用vue中的ajax)

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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值