立诚勿怠,格物致知
It's all about connecting the dots

nginx做接口转发

有时候服务端不自带web容器,然后接口又没有做跨域支持,前端并不想在服务器上多部署一个服务,那么如果服务器上使用了nginx的话,可以直接通过配置nginx达到请求转发的目的。

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
    }

    location /hcm {
        proxy_pass http://127.0.0.1:8081;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header    X-Read-IP    $remote_addr;
        proxy_set_header    X-Forwarded-For    $proxy_add_x_forwarded_for;
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

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

需要注意的是这里的配置:

location /hcm {
    proxy_pass http://127.0.0.1:8081;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header    X-Read-IP    $remote_addr;
    proxy_set_header    X-Forwarded-For    $proxy_add_x_forwarded_for;
}

这里的location /hcm配上后面的proxy_pass http://127.0.0.1:8081;会将所有指向/hcm路径下的请求都转发到服务器上8081端口对应的服务上,请求路径本身不会发生变化,即/hcm/test.do的请求会被转发到8081服务的/hcm/test.do接口上。

如果这里把location /hcm换成location /hcm/,则转发后的请求路径只会保留/hcm之后的部分,即/hcm/test.do的请求会被转发到8081服务的/test.do接口上。

赞(1) 打赏
文章名称:《nginx做接口转发》
文章链接:https://www.orzzone.com/nginx-h5-proxy.html
商业联系:yakima.public@gmail.com

本站大部分文章为原创或编译而来,对于本站版权文章,未经许可不得用于商业目的,非商业性转载请以链接形式标注原文出处。
本站内容仅供个人学习交流,不做为任何投资、建议的参考依据,因此产生的问题需自行承担。

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力提供更多优质内容!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册