Nginx代理:根请求的重写规则

ofs*_*dio 2 nginx

我在端口80上安装了nginx,在nginx后面的端口2368上安装了节点应用程序

nginx配置看起来像这样

server {
    server_name domain.com www.domain.com;
    listen 80; 
    location / {
        proxy_pass http://localhost:2368;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
    } 
}
Run Code Online (Sandbox Code Playgroud)

此配置完全按预期工作.例如/请求变成http://localhost:2368/,/post/mypost变成http://localhost:1234/post/mypost等等.

我想要的是只有/请求变成了http://localhost:2368/latestpost/.所有其他请求的处理方式与上面的示例相同.日Thnx!

Ale*_*Ten 8

你可以使用rewrite指令:

server {
    server_name domain.com www.domain.com;
    listen 80; 
    location / {
        rewrite ^/$ /latestpost/ break;
        proxy_pass http://localhost:2368;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
    } 
}
Run Code Online (Sandbox Code Playgroud)

或在不同的位置:

server {
    server_name domain.com www.domain.com;
    listen 80;
    location = / {
        rewrite ^.* /latestpost/;
    }
    location / {
        proxy_pass http://localhost:2368;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
    } 
}
Run Code Online (Sandbox Code Playgroud)

第二个变体稍微高效,因为它不会尝试重写每个请求.但我猜,差异将是不明显的.