nginx代理静态页面和后端服务(spring cloud gateway)
nginx配置nginx.configworker_processes1;events {worker_connections1024;}http {includemime.types;default_typeapplication/octet-stream;upstream proxy {#配置代理后端端口,多台服务器可以配置多个节点server localhost:9999 weight
·
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的路径下!!!
你品,细细的品!
更多推荐
已为社区贡献3条内容
所有评论(0)