4

I have an nginx server with SSL enabled. As it operates on a different port (than 443), sometimes it receives plain HTTP requests instead of HTTPS. I'd like to set up a redirection for that to replace the scheme automatically, I tried this code:

error_page 497 https://$host:$server_port$request_uri;

But the problem here that as the server operates in a VM and the port is forwarded to a different port, it redirects to an invalid port (from which the server got the request).

My question is: how can I parse/get the port from the request rather than the port from the server received the request?

8

Hopefully not too little too (eight months!) late. I had a similar question myself, to use the original request port in nginx.conf.

nginx $http_name variable

$http_name: arbitrary request header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores

$http_host should therefore contain the request 'Host' header, if that helps.

e.g. localhost:8020

|improve this answer|||||
  • It worked, thank you! Here is the final solution: error_page 497 https://$http_host$request_uri; – riska May 10 '18 at 11:24
0

This question is pretty much a duplicate of this one:

How to forward non-http requests on port 80 to another port?

There they receive non-HTTP requests on port 80, you get non-HTTPS requests on a port 443 alternative. Other than that, the idea is the same.

Nginx modules exists to do more with TCP packets:

http://nginx.org/en/docs/stream/ngx_stream_core_module.html

https://github.com/yaoweibin/nginx_tcp_proxy_module

|improve this answer|||||
  • Not really, it's not just a simple redirect, let me explain: I request the url https://localhost:8443/ from my browser and this request get forwarded to my VM's port 443 where it get handled. But if I use HTTP, then the url is http://localhost:8443/ and it hits the server on the port 443. So if I use the $server_port, then I get redirected to https://localhost:443. Additionally, as it's a VM, I can't be sure that it's always port 8443 so I can't hardcode it but I have to parse it from the request somehow. – riska Jul 12 '17 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.