My nginx instance is behind a SSL terminated load balancer, and I want all urls to hit https
endpoints, which means http
to be redirected to https
.
All is well when urls have a trailing slash. They all get redirected nicely:
#!/bin/sh
do_curl() {
echo "\n$ do_curl $1"
curl -L -s -D - "$1" -o /dev/null | grep -iE 'Location|HTTP/|server'
}
$ do_curl https://example.com/
HTTP/2 200
$ do_curl http://example.com/foo/
HTTP/1.1 301 Moved Permanently
Location: https://example.com/foo/
HTTP/2 200
$ do_curl https://example.com/foo/
HTTP/2 200
But when the same urls have no trailing slash, nginx's try_files
seems to be issuing a http
redirect always:
bad.png
Here's my nginx vhost.conf
:
server {
listen 80;
root /app/;
index index.html index.htm;
# This 'if' block is only needed because my SSL-terminated Load balancer proxies both http and https to nginx.
# If my Load balancer only proxied https to nginx, and dropped http, this 'if' block can be omitted.
if ($http_x_forwarded_proto = "http") {
return 301 https://$host$request_uri;
}
location / {
try_files $uri $uri/ =404;
}
}
How do I get nginx's try_files
to redirect directly with the https
$scheme
when it hits the $uri/
parameter (2nd parameter in my try_files
above) and successfully finds a file matching $uri/<index>
(where index
is defined by the index
directive in the nginx config above)?
I searched similar questions such as here, here, or here but still could not find anything remotely relevant.