Http POST drops port in URL

2020-05-19 05:20发布

问题:

I have a webapp built with Django. I'm currently running it off a laptop at home behind a router.

I have the router configured to route all traffic sent to a specific port to that laptop.

I have Nginx as a reverse proxy for Apache, using mod_wsgi to run Django.

My problem is this: when I try to submit any POST form, the port # gets removed from the url (e.g. 209.245.23.201:1552/login/ becomes 209.245.23.201/login/)

Naturally, this breaks. What causes this (Nginx, Apache, Django?) and how can I fix it?

Thanks in advance.

EDIT: It appears that the forms DO submit, but I think the redirect fails.

EDIT 2: The problem is definitely either with Nginx, or the interaction between Nginx and Apache. I tried the setup with Apache as the only server, running django, and it worked fine. So either Nginx is dropping the port, or somehow Apache is getting confused by Nginx acting as the proxy.whatever

回答1:

I have the same problem with my development server. After some internet search I've found this discussion (nginx, apache, and odd admin error) where the solution is to modify the proxy configuration of nginx.

The configuration setting to modify is:

proxy_set_header            Host $host;

the solution is to add the port number:

proxy_set_header            Host $host:$server_port;

In my ngnix + apache2 (with worker mpm) + django now all works well.



回答2:

You want to pass on the original HTTP Host header, which arrived at nginx:

proxy_set_header Host $http_host;

This appears to be a bug with the default configuration of nginx in Debian/Ubuntu, which uses only $host: $host will not contain the $server_port. (This is configured in /etc/nginx/proxy_params for the Debian/Ubuntu package, and you might override it in your configuration after including it.)

Please note that $host:$server_port is different from $http_host. See http://wiki.nginx.org/HttpCoreModule#.24host for an explanation.

Reported and fixed in Debian: http://bugs.debian.org/733016



回答3:

Given everything you're concerned with is clear HTTP (unlike something like AJP for instance) I'd run a protocol analyser such as Wireshark on the host and determine at which point the redirect is introduced.



回答4:

Check the error logs. On Linux mine are at /var/log/apache2. Just running a search for error.log should turn it up.



回答5:

If you find that this occurs with a url derived from the get_absolute_url() method of a model, you should use pass that path to HttpRequest.build_absolute_url() in order to prepend the hostname and port to the path.