windows 平台下单机部署nginx 实现api网关效果

1 下载 windows 版本的nginx

链接:https://pan.baidu.com/s/1EPcqgLdcq7y96OcZ2LInuw
提取码:0ris

 

2 下载解压压缩包,不需安装

1) 解压压缩文件夹,进入 nginx-1.20.2 目录,然后在目录下打开cmd,启动命令 start nginx
2) 查看nginx任务进程是否存在,命令 tasklist /fi "imagename eq nginx.exe",如果没找到,去logs文件夹看日志(error.log),如果提示端口被占用,修改 conf 文件夹下的
配置文件 nginx.conf 修改 监听listen 端口,(修改 nginx.conf 前建议都先进行备份)
浏览器打开 localhost:8080 其中 localhost 是对应的servername,8080是监听的端口,如果打开的网页显示 Welcome to nginx 就说明启动成功了
3) 修改了nginx配置重载nginx配置命令: nginx.exe -s reload ,如果报错 CreateFile() "E:\Tools\nginx\nginx-1.20.2/logs/nginx.pid" failed (2: The system cannot find the file specified) ,可能是nginx未启动
4) 停止Nginx:使用nginx -s stop来快速停止nginx,使用nginx -s quit 完整的停止nginx。

 

3 配置nginx实现类似网关功能

现在需要在nginx配置访问 http://localhost:8080/api/nginx/Test/Ping 转到访问 http://localhost:5143/Test/Ping

nginx 配置如下:

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    # 定义转发分配规则
    upstream api_nginx {
        server localhost:5143;
    }

    server {
        listen       8080;
        server_name  localhost;

        # http://localhost:8080/api/nginx/Test/Ping   转到  http://localhost:5143/Test/Ping
        location ^~/api/nginx/ {
            proxy_redirect off;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://api_nginx/; 
        }

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

注意 proxy_pass 路径的 / 代表会覆盖 /api/nginx 的路径

4 测试

 

 

 

posted @ 2023-04-14 23:16  温故纳新  阅读(147)  评论(0编辑  收藏  举报