nginx搭配Spring Cloud Gateway 搭建域名訪問環境

1. 安裝SwitchHosts,方便切換本地host文件

安裝鏈接:https://github.com/oldj/SwitchHosts/releases
在這裏插入圖片描述

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 的調用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章