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

时间:2014-12-09 07:01:42

标签: 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;
    } 
}

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

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

1 个答案:

答案 0 :(得分: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;
    } 
}

或在不同的位置:

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;
    } 
}

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