9

#Nginx 用proxy_pass做反向代理返回400错误

 4 years ago
source link: https://xmanyou.com/nginx-proxy_pass-passing-encoded-url-to-proxy-server-with-error-code-400/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
25 August 2021 / Nginx

#Nginx 用proxy_pass做反向代理返回400错误

前端web项目,经常会遇到跨域访问的问题,利用Nginx的proxy_pass可以很轻松的配置反向代理,解决这个问题。

假设资源服务器是asset-server,用以下配置,可以把asset-server/app 挂载到 server/app

  location ^~ /app {
    proxy_pass http://asset-server;
  }

这样能解决大部分的问题,但是当路径包含特殊字符,例如空格等,需要进行转义urlencode时,就回遇到问题。

需要对uri进行重写:

  location ^~ /app {
    rewrite  ^ $request_uri;            # get original URI
    rewrite  ^/app/(.*)  app/$1 break;  # drop /foo, put /bar
    return 400;   # if the second rewrite won't match

    proxy_pass http://asset-server/$uri;
  }

特别注意
如果有多层代理,每一层都需要rewrite。

  location /api/ {
    rewrite ^ $request_uri;
    rewrite ^/api/(.*) $1 break;
    return 400;
    proxy_pass http://127.0.0.1:82/$uri;
  }

阿斌

Read more posts by this author.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK