I'm trying nginx for first time, and I do it with docker. Basically I want to achieve the following architecture
http
request to be redirected to https
I'm generating the /etc/nginx/conf.d/default.conf
file with some environment variables on start up. That file is then included inside the http
context of the default.conf file, thus bringing some limitation to what I can configure. (related issue)
You can see my current nginx.conf
file here (file is quite large to embed here).
And you can see the docker-compose.yml
file here.
I can't actually make that any call to http://(app/api).example.com
to be redirected to its https
version, I've tried with this without success: (see the the above linked file)
server {
listen 80 ssl;
listen 443 ssl;
listen [::]:80 ssl;
listen [::]:443 ssl;
server_name api.dev.local;
if ($http_x_forwarded_proto = "http") {
return 301 https://$server_name$request_uri;
}
# more code...
}
Any recommendations regarding to the my actual configs are more than welcome in the comments sections! I'm just starting to use nginx and thus reading tons of artciles that provide code snippets that I simply copy and paste after reading what are they needed for.
The https
protocol is an extension to http
, so they are different protocols to an extent. At the moment your server does not expect http
on :80, it rather expects https
due to the setting listen 80 ssl
. This causes the error.
You need to separate handling of http
requests on :80, which should be redirected to https
on :443, from handling https
on :443, which should be handled normally.
This can be done by splitting out another server
configuration block for http
on :80:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
...and removing listening on :80 from the current block:
server {
listen 443 ssl;
listen [::]:443 ssl;
# more code...
}
The following blog article gives more details if needed https://bjornjohansen.no/redirect-to-https-with-nginx