如何在Nginx中代理重写的URL?

时间:2017-10-25 11:20:29

标签: nginx proxy url-rewriting

我有以下配置:

js_include /etc/nginx/scripts/encode_request.js;
js_set $encoded_request re_encode_url;
log_format logEncoded $encoded_request;

server {
       listen 443 ssl;
       listen [::]:443;

       server_name myfirst-domain.com;

        ssl on;
        ssl_certificate         /etc/ssl/certs/cert.cer;
        ssl_certificate_key     /etc/ssl/private/cert.key;

       location / {
                proxy_set_header        Host $host;
                proxy_set_header        X-Real-IP $remote_addr;
                proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header        X-Forwarded-Proto $scheme;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";

                if ($request_uri ~ ^/lool/https%3A/alf.mydomain.com/(.*)$){
                     access_log /var/log/nginx/access.log logEncoded; #Output the encoded url to the logs. (For debugging purposes)
                     rewrite ^/lool/https%3A/alf.mydomain.com/(.*)$ $encoded_request;
                }
                proxy_pass              https://localhost:9980;

        }
}

其目的是过滤包含后端服务所需的已解码URL的URL请求。问题是虽然请求URL已成功编码,但它没有被代理到后端服务,而是我得到原始解码的URL,这反过来导致错误,尽管我在access.log中获得了正确编码的URL输出。
不是一个NGINX或网络服务器saavy人,所以我很欣赏一些关于我做错了/丢失的指示。
另一件可能值得注意的事情是请求升级到客户端和服务器之间的websocket通信,我代理的是。
我在Debian Jessie上使用NGINX 1.13.6。

1 个答案:

答案 0 :(得分:0)

我最后使用nginScript解决了这个问题。 我抛出了条件,只是在nginScript中做了所有事情,因此简化了虚拟主机文件(或服务器块):

server {
   listen 443 ssl;
   listen [::]:443;

   server_name myfirst-domain.com;

    ssl on;
    ssl_certificate         /path/to/ssl/certificate;
    ssl_certificate_key     /path/to/ssl/certificate/key;
    location / {
            proxy_set_header        Host $host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto $scheme;

            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";

            #Optional
            access_log /var/log/nginx/ll_access.log;
            error_log /var/log/nginx/ll_error.log;

            proxy_pass    https://127.0.0.1:9980$encoded_request;
    }

}