nginx搭配Spring Cloud Gateway 搭建域名访问环境

1. 安装SwitchHosts,方便切换本地host文件

安装链接:https://github.com/oldj/SwitchHosts/releases
nginx搭配Spring Cloud Gateway 搭建域名访问环境_第1张图片

2. 修改nginx.conf的配置文件

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    # gzip  on;
    # 配置微服务网关的地址
    upstream gulimall{
        server 192.168.202.1:88;
    }
    # 为了防止 nginx.conf 文件膨胀过大,因此采用该方法引入其他配置文件
    include /etc/nginx/conf.d/*.conf;
}

3. 修改 /conf.d/default.conf 文件

server {
	# 监听来自 gulimall.com 域名的 80 端口的请求
	# 这里的域名与 SwitchHosts 里面配置的域名一致
    listen       80;
    server_name  gulimall.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
    	# proxy_pass 将监听到的请求转发到 nginx.conf 文件中的 对应的upstream 中,即 192.168.202.1:88 (网关地址)。即在此完成了访问网址-> nginx -> 网关
        proxy_pass http://gulimall;
        # proxy_set_header 给通过 nginx 的请求添加请求头的部分信息,这里需要注意,经过 nginx 的请求会丢失请求头的部分信息。这里添加域名信息,方便在网关处拦截并转发到对应的微服务。
        proxy_set_header Host $host;
    }

    #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   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

4. Spring Cloud GateWay 配置

spring:
  cloud:
    gateway:
      routes:   
        - id: gulimall_host_route
          uri: lb://guli-mall-product
          predicates:
            - Host=**.gulimall.com

注意将该拦截条件放在最后,以免影响通过该域名的 api 的调用

你可能感兴趣的:(日常记录)