search

Home  >  Q&A  >  body text

nginx reverse proxy and add a directory

For example, I want to access 127.0.0.1:9000 through 127.0.0.1/play/
My current configuration is as follows:

location / {
        root   F:\Personal\ck;
        index  index.html;
}
location ~ ^/play/ {
        proxy_pass   http://127.0.0.1:9000;
        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_redirect off;
}

When I actually accessed 127.0.0.1/play/, it accessed 127.0.0.1:9000/play/. I was very confused. Didn't it directly access the 9000 port, but put the directory name behind it?

天蓬老师天蓬老师2755 days ago407

reply all(2)I'll reply

  • 阿神

    阿神2017-05-16 17:23:03

    Because you requested /play/ and this request was passed to http://127.0.0.1:9000. The path of this request will also be passed.

    What you want can come true,

    location ~ ^/play(/?)(.*){
        proxy_pass http://127.0.0.1:9000/$;
    }

    The meaning of this code is to pass the request for /play/xx to http://127.0.0.1:9000/xx

    Better way

    location /play {
            proxy_pass   http://127.0.0.1:9000/;
    }

    Pay attention to the '/' at the end

    Look here
    http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 17:23:03

    Because proxy_pass is just a reverse proxy, it cannot rewrite URL rules. It only changes the host name.
    If you want to remove the last thing, you have to use rewrite

    location ~^/play/ {
        proxy_pass    http://127.0.0.1:9000;
        rewrite       "^/play(.*)$"  break;
        ...
        }

    reply
    0
  • Cancelreply