How to force HTTP redirect to HTTPS on NGINX

Asked

Viewed 337 times

0

I’m deploying an app made with nuxt.js. For hosting, I’m using the Digital Ocean + Server Pilot.

I’m having trouble forcing the redirect of HTTP for HTTPS. Below is the configuration Nginx that I’m wearing.

map $sent_http_content_type $expires {
    "text/html"                 epoch;
    "text/html; charset=utf-8"  epoch;
    default                     off;
}
server {
    listen 80;
    server_name            admin.domain.com;

    gzip            on;
    gzip_types      text/plain application/xml text/css application/javascript;
    gzip_min_length 1000;

    location / {
        expires $expires;
        proxy_redirect                      off;
        proxy_set_header Host               $host;
        proxy_set_header X-Real-IP          $remote_addr;
        proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto  $scheme;
        proxy_read_timeout          1m;
        proxy_connect_timeout       1m;
        proxy_pass                          http://127.0.0.1:3000;
    }
}
server {
    listen    443 ssl default_server;
    listen    [::]:443 ssl default_server;
    ssl_certificate_key    ssl/_default.key;
    ssl_certificate        ssl/_default.crt;
    return    444;
}

Access https://admin.domain.com, it works; if you access http://admin.domain.com, it does not redirect to https and I get a "not safe" sign, the little red chair

NOTE: I would like to configure/resolve this block server, because in the future I will have other servers, for example blog.domain.com

2 answers

2

In his server{ listen: 80; ... (http) you can do the following:

server {
    listen 80;
    server_name            admin.domain.com;

    # Use isso ou ele dentro do location / {...}
    return 301 https://$host$request_uri; 
    #      ^
    #      Diz para o browser o link foi Movido Permanentemente 

    # location / {
    #       return 301 https://$host$request_uri;
    # }
}

NOTE: If a POST for HTTP this redirect method will not send the data to HTTPS

References:
Serverfault - In Nginx, how can I rewrite all http requests to https while maintaining sub-Omain?
NGINX - Pitfalls and Common Mistakes#Taxing Rewrites
Wikipedia - HTTP Status code 301

-1

Hello, I was able to redirect to https using the condition below inside /etc/nginx/sites-enabled/default

server {

    ...

    if ($scheme = http) {
      return 301 https://$host$request_uri;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.