6

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?

Andras
  • 165

3 Answers3

14

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

wilee
  • 256
0

A user named @wilee mentioned that they found wilee's solution helpful. They stated that their Nginx service was configured to listen on port 80 in the Docker container. However, when they ran the Nginx container, they mapped port 8000 to port 80. Initially, they used the following configuration:

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

This resulted in redirects from

  • http://192.168.0.38:8000 to
  • https://192.168.0.38:80.

After making changes to their configuration as follows:

error_page 497 https://$http_host$request_uri;

They were able to resolve the issue and the configuration worked as expected.

djdomi
  • 2,287
kingjh
  • 1
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

JayMcTee
  • 4,111