Redirecting IP Traffic to HTTPS – NGINX Tricks Part 1

nginx-logo-rgb-large

Lately I had a peculiar issue, I wanted to secure a web server running NGINX with HTTPS using Let’s Encrypt, but almost all traffic to said web server request the web page using the IP address of the server, since the web server is only there to tell people about the primary service running on the server. (Yes, this is a public NTP server that’s part of the NTP Pool Project if you had figured that out).

As you might know, Let’s Encrypt needs to have a server name defined in the web server configuration to make autoconfiguration of the web server work, so that rules out the “direct IP” traffic. Also, I’m fairly certain that Let’s Encrypt won’t issue a certificate directly to an IP. This puts us into somewhat of a dilemma, we can either serve the direct IP traffic over HTTP, and traffic that has the DNS name of the server defined in the HTTP request over HTTPS, but that’s not rather elegant.

The solution I settled on is to do what certbot does for HTTP-to-HTTPS redirects. Basically, any traffic that arrives on port 80 without specifying a hostname in the request gets redirected to HTTPS.

All you have to do is to insert the following server block above what certbot already put in the server configuration.

server {
   if ($host = PUBLIC_IP) {
       return 301 https://server1.example.com$request_uri;
   }

       listen 80;
       listen [::]:80;

       server_name PUBLIC_IP;

   return 404;
}

As you can see, what we do for all incoming traffic to the public IP on port 80 is to send a 301 Moved Permanently with the URL and specifying HTTPS at the same time. This is coincidentally the best practice for upgrading incoming sessions from HTTP to HTTPS as well.



Categories: Tech

Tags: , , , , , , ,

2 replies

Trackbacks

  1. Enabling HTTP/2 on NGINX – NGINX Tricks Part 3 – Grumpy Techie
  2. Disabling Insecure Ciphers on NGINX – NGINX Tricks Part 4 – Grumpy Techie

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: