I've got an Amazon ELB that listens for http and https traffic. Instances behind it have nginx on port 80. Http only. So ELB forwards both https and http to http of nginx.

When I make an https request to a folder like https://example.com/folder it is redirected automatically to a slash version http://example.com/folder/ but protocol becomes http. Folder contains index.html file. I assume that's what makes it work.

Is there any way to fix this? I.e. make it redirect to https instead of http. I can not enforce https globally.

My config:

http {
map $http_x_forwarded_proto $thescheme {
    default $scheme;
    https https;

server {
    listen 80;
    server_name example.com;
    location / {
        root /var/www/html;
        add_header X1 $scheme;
        add_header X2 $thescheme;
        index index.html;

I've added X1 and X2 headers to check what protocol nginx thinks is used and if X-Forwarded-Proto header is added by ELB. X1 is http, X2 is https for the example request.

I found that adding

if (-d $request_filename) {
    rewrite [^/]$ $thescheme://$http_host$uri/ permanent;

inside location helps but wondering if there's a better solution.

  • Instead of using rewrite, I would recommend to follow best practices and use the return directive instead. Using this could look like the following:

    if ($http_x_forwarded_proto = 'http') {
        return 301 https://example.com$request_uri;
  • Additionally, to enforce the use of HTTPS for all clients which made a HTTPS requests once, think about adding a HTTP Strict Transport Security (HSTS) header. HSTS is

    a web security policy mechanism which helps to protect websites against protocol downgrade attacks and cookie hijacking.

    To make use of it, the directive could look like the following:

     add_header Strict-Transport-Security max-age=31536000;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.