Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect HTTP to HTTPS with NGINX [closed]

I have a couple of applications that I maintain at my work and noticed that some employees are able to use the non-secure paths to those applications such as: example.com, www.example.com. Using either of those paths will direct them to the HTTP path instead of HTTPS, unless they specify HTTPS in the url. We currently use nginx as our gateway, but I did not do the initial configuration of our nginx gateway, so I don't really know what works and what doesn't.

Here is a snippet of our nginx.conf file

server{
        listen  80 default_server;
        listen  [::]:80 default_server;
        server_name localhost;

        location / {
            proxy_pass http://localhost:3000;
        }
}

# Settings for a TLS enabled server.

    server {
        listen      443 ssl http2 default_server;
        listen      [::]:443 ssl http2 default_server;
        server_name     localhost;

        ssl_certificate "/etc/nginx/ssl/domain-crt.txt";
        ssl_certificate_key "/etc/nginx/ssl/domain-key.txt";
        ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;

        ## More configuration below this...
    }

I tried doing a return in the listen 80 section but this did not work:

server{
        listen  80 default_server;
        listen  [::]:80 default_server;
        server_name localhost;
        return 301 https://$host$request_uri;

        location / {
            proxy_pass http://localhost:3000;
        }
}

I reloaded nginx with the corrections and I was still able to connect to the http paths without it redirecting to https. I don't know if this has something to do with the server_name being localhost because I've only seen examples online where they are redirecting to the actual domain name, but this is how our applications are setup and I don't know if changing that will have effects on the connectivity of our applications. If anyone has any ideas or suggestions on how I could get a redirect to work properly, that would be great. Thanks!

like image 317
Michael Avatar asked Feb 06 '26 05:02

Michael


1 Answers

You're missing the semicolon at the end, also you should get rid of the proxy_pass since that overrides the behavior.

server {
    listen  80 default_server;
    listen  [::]:80 default_server;
    server_name localhost;

    location / {
        return 301 https://$host$request_uri;
    }
}
like image 195
flyx Avatar answered Feb 09 '26 11:02

flyx