irpas技术客

nginx代理静态页面和后端服务(spring cloud gateway)_黎明晓月

大大的周 5630

nginx配置

nginx.config

worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; upstream proxy { #配置代理后端端口,多台服务器可以配置多个节点 server localhost:9999 weight=1; } sendfile on; keepalive_timeout 65; server { listen 9010; server_name localhost; #此处可以把静态分离的前端页面放以相对路径在nginx中 root html; index index.html; #location / { #root html; #index index.html index.htm; #} #location /user/ { #proxy_set_header Host $host; #proxy_set_header x-forwarded-for $remote_addr; #proxy_set_header X-Real-IP $remote_addr; #proxy_pass http://localhost:9012/; #} location / { location ~* \.(gif|jpg|jpeg|png|bmp|swf|js|css)$ { #允许nginx代理静态页面 expires 30d; if (-f $request_filename){ break; } } if (!-e $request_filename){ proxy_pass http://proxy; #在这里设置一个代理,和upstream的名字一样 } } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }

静态页面存放

spring cloud gateway

引入依赖:

<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> </dependencies>

配置文件:

spring: application: name: gateway-service #注册到consul配置 cloud: consul: host: localhost port: 8500 discovery: enabled: true register: true healthCheckInterval: 30s # 本地调试 instanceId: ${spring.application.name} # tags: prefer-ip-address: true ip-address: localhost #此处为重点 gateway: routes: #配置路由: 路由id,路由到微服务的uri,断言(判断条件) - id: user-service #保持唯一 uri: http://127.0.0.1:9012/ #目标为服务地址可以换成服务名称 predicates: - Path=/user/** #路由条件 path 路由匹配条件 filters: - StripPrefix=1 #此处为过滤(第一个路由条件 path 路由匹配条件)

注: 假如请求是: http://127.0.0.1:4040/api/test nginx配置中

proxy_pass http://127.0.0.1:4041/;

加/ --被代理到–> http://127.0.0.1:4041/test 不加/ --被代理到–> http://127.0.0.1:4041/api/test 也就是说,加了/会被代理到指定的路径,不加/会被代理到指定路径+api的路径下!!! 你品,细细的品!


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #Cloud #gateway #1events