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

Keeping Headers During NGINX Rewrite

· 52CE 我爱测

I am attempting to set up an NGINX proxy to redirect all requests to one of two servers based on the contents of a query string argument. Essentially: https://my.site.com/api/...&server=a should redirect to https://a.site.com/api…

问题原文

原帖链接 · JimmidyJoo · CC BY-SA 3.0

I am attempting to set up an NGINX proxy to redirect all requests to one of two servers based on the contents of a query string argument. Essentially:

https://my.site.com/api/...&server=a

should redirect to

https://a.site.com/api/...&server=a

and

https://my.site.com/api/...&server=b

should redirect to

https://b.site.com/api/...&server=b

I appear to have a config that does the basic work of rewriting the hostname and keeping the query string intact:

error_log /dev/stdout info;
worker_processes 1;

events {
    worker_connections 1024;
    accept_mutex off;
}

http {
    access_log /dev/stdout combined;
    sendfile on;

    server {
        listen 443 ssl;
        server_name         $hostname;
        ssl_certificate     /etc/ssl/nginx.crt;
        ssl_certificate_key /etc/ssl/nginx.key;
        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers         HIGH:!aNULL:!MD5;

        location ~ /api/ {
            if ($arg_server !~ "^(a|b)$") { return 404; }
            rewrite ^ $scheme://my.site.$arg_server.com$uri;
        }
    }
}

However, I cannot seem to get all the headers in the original request to survive the journey -- the Authorization header, for example, does not seem to arrive at https://[server].site.com/api/...

My understanding was that all headers were kept by default? Is that not true?

已采纳解答

原帖链接 · JimmidyJoo · CC BY-SA 3.0

I was able to do what I wanted to achieve by getting rid of rewrite and replacing it with proxy_pass and resolver entries:

    location /api/ {
        if ($arg_server !~ "^(a|b)$") { return 404; }

        resolver dns.site.com;
        proxy_pass $schemes://my.site.$arg_server.com$request_uri;
    }

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

资料来源与适用范围

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

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

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