大网数据广告活动
服务器运维问答

How do i configure nginx to use part of a URL as a header?

· 52CE 我爱测

I am trying to get a server application running which supports multiple customers. They should each access the app with their own URL, e.g. http://localhost:8082/customer1/config , but the application needs to have the customer s…

问题原文

原帖链接 · Johannes Dorn · CC BY-SA 3.0

I am trying to get a server application running which supports multiple customers.

They should each access the app with their own URL, e.g. http://localhost:8082/customer1/config, but the application needs to have the customer specific part as a request header instead. The request should be redirected to http://localhost:9002/config.

I can achieve this if i write a location rule for each customer:

server {
    listen          8082;
    server_name     localhost;
    root            /;

    location /customer1/ {
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_cookie_path ~*^/.* /;
            proxy_set_header X-customer customer1;
            proxy_pass http://127.0.0.1:9002/;
            proxy_redirect off;
    }
}

How can i configure nginx so it takes any customer name and puts it into the header?

已采纳解答

原帖链接 · Johannes Dorn · CC BY-SA 3.0

Here is how i made this work:

location ~ ^/(?!vaadinServlet|customer)(.+?)/(.*) {
       proxy_set_header X-Forwarded-Host $host;
       proxy_set_header X-Forwarded-Server $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $host;
       proxy_cookie_path ~*^/.* /;
       proxy_set_header X-customer $1;
       proxy_pass http://127.0.0.1:9002/$2;
       proxy_redirect off;
}

Thanks to Tim for the inspiration.

Note that this also prevents URLs starting with vaadinServlet or customer from being selected. If you don't need special treatment for such keywords, it would suffice to use

location ~ ^/(.+?)/(.*) {
    ...
}

If the URL part to be handled doesn't have to appear at the start (i.e. after the server name), remove the ^.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-05-25)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。