Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite nginx host and proxypass to squid

I want to achieve the following:

Request Host:

http://example.com.proxy.myserver.com

Should be rewritten to

http://example.com

and passed to a squid server via nginx proxypass.

server {
  listen 80;
  server_name ~^(?<subdub>.*)\.proxy\.myserver\.com$;
  location / {
    rewrite ^ $scheme://$subdub break;
    proxy_set_header  X-Real-IP $remote_addr;
    proxy_set_header  Host $scheme://$subdub;
    proxy_set_header  Request-URI $scheme://$subdub;
    proxy_pass http://localhost:3128;
    proxy_redirect off;
  }
}

The problem is, that nginx redirects this request immediately to http://example.com

Any ideas how to get this working?

like image 221
Sebastian Avatar asked Nov 12 '22 08:11

Sebastian


1 Answers

301 redirect is exactly what nginx shall do with that rewrite rule: because you put $scheme://$subdub at the replacement part, nginx will do a 301, ignoring that "break" flag.

If the replacement string begins with http:// then the client will be redirected, and any further rewrite directives are terminated.

Are you trying to "rewrite" or "redirect"? If it's just for rewrite, you can remove that rewrite directive:

    rewrite ^ $scheme://$subdub break;

and it will work because your upstream server could rely on the HOST header to determine the traffic target (virtual hosting).

Also your host header sent to the upstream server is wrong. It should be

    proxy_set_header  Host $subdub;

$scheme should not be put in the Host header.

like image 171
Chuan Ma Avatar answered Nov 26 '22 12:11

Chuan Ma