nginx proxypass 重写基本 URL

nginx proxypass 重写基本 URL

我正在尝试设置 Nginx 以使用 proxy_pass 将请求转发到多个后端服务。

其中一些不支持在子文件夹下访问,所以我必须添加重写以剥离附加的子文件夹,以允许从同一端口访问它们。

关于改进重写有什么建议吗?

卷曲输出;

:~$ curl -I -k https://example.net/internal
HTTP/1.1 404 Not Found
Server: nginx/1.0.5
Date: Thu, 19 Jan 2012 22:30:46 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Content-Length: 145

:~$ curl -I -k https://example.net/internal/
HTTP/1.1 200 OK
Server: nginx/1.0.5
Date: Thu, 19 Jan 2012 22:31:12 GMT
Content-Type: text/html
Connection: keep-alive
Content-Length: 1285
Accept-Ranges: bytes
Last-Modified: Wed, 18 Jan 2012 01:35:21 GMT

配置文件;

代理配置文件

location /internal {
    rewrite           ^/internal/(.*) /$1 break;
    proxy_pass        http://localhost:8081/internal;
    include proxy.inc;
}
.... more entries ....

站点启用/主要

server {
    listen 443;

    server_name example.com;
    server_name_in_redirect off;

    include proxy.conf;

    ssl on;
}

代理公司

proxy_connect_timeout   59s;
proxy_send_timeout      600;
proxy_read_timeout      600;
proxy_buffer_size       64k;
proxy_buffers           16 32k;
proxy_pass_header       Set-Cookie;
proxy_redirect          off;
proxy_hide_header       Vary;

proxy_busy_buffers_size         64k;
proxy_temp_file_write_size      64k;

proxy_set_header        Accept-Encoding         '';
proxy_ignore_headers    Cache-Control           Expires;
proxy_set_header        Referer                 $http_referer;
proxy_set_header        Host                    $host;
proxy_set_header        Cookie                  $http_cookie;
proxy_set_header        X-Real-IP               $remote_addr;
proxy_set_header        X-Forwarded-Host        $host;
proxy_set_header        X-Forwarded-Server      $host;
proxy_set_header        X-Forwarded-For         $proxy_add_x_forwarded_for;
proxy_set_header        X-Forwarded-Ssl         on;
proxy_set_header        X-Forwarded-Proto       https;

答案1

我们可以把你的变得rewrite更丑陋以解释那个字符串(/internal)而不允许意外的匹配......(如果你愿意,你会想知道((?:/.*|))你的斜线在哪里或类似的野兽)但丑陋的维护性较差。

我倾向于说就这样做:

location /internal {
    rewrite           ^/internal$ https://example.net/internal/ permanent;
    rewrite           ^/internal/(.*) /$1 break;
    proxy_pass        http://localhost:8081/internal;
    include proxy.inc;
}

相关内容