http redirect to https for nginx regular and unconventional ports

Original link: https://hellodk.cn/post/1074

standard port

The regular port is very simple, use two server blocks, one listens to 80 for jumping, and one listens to 443 for actual serving

 server { listen 80 default_server; server_name xxx.example.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name xxx.example.com; ssl_certificate /path/to/fullchain.pem; ssl_certificate_key /path/to/privkey.pem; ssl_trusted_certificate /path/to/chain.pem; ... }

There are several ways for http to redirect all traffic to https. The above is a recommended way of writing.

non-standard port

If I use the port 37878 as the service port, users visit http://xxx.example.com:37878/ and we will automatically redirect it to https://xxx.example.com:37878/

Using the above method will not work.

nginx creates a custom HTTP status code that allows jumping from http to https, the status code is 497 . This is only required when running SSL on a non-regular port/custom port, otherwise the normal port jump setting method is generally used.

only one server block

 server { listen 37878 ssl http2; server_name xxx.example.com; ssl_certificate /path/to/fullchain.pem; ssl_certificate_key /path/to/privkey.pem; ssl_trusted_certificate /path/to/chain.pem; error_page 497 https://$server_name:37878$request_uri; ... }

Add the above line error_page 497 https://$server_name:37878$request_uri; and you’re done.

Found through curl that this is a 302 temporary redirect HTTP/1.1 302 Moved Temporarily .

This article is reprinted from: https://hellodk.cn/post/1074
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment