gabrielesan
gabrielesan

Reputation: 15

Configuring Nginx - routing traffic from HTTP to HTTPS and BAD REQUEST error (local host, no domain)

I'm trying to configure my Nginx in a way so that all HTTP requests are redirected to HTTPS. This is a testing environment and I don't have the domain, hence, I'm not sure whether the redirect can function properly. The host part is simply 127.0.0.1. This is the current configuration:

    server {
    listen 80;
    listen [::]:80;

    server_name _;
    return 301 https://$host$request_uri;
    }

    server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name _;
    ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
    ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key; 
    ...

I also tried: removing server_name _; putting the return 301 in a location block; adding further ssl settings, such as ssl_session_timeout, ssl_protocols, ssl_prefer_server_ciphers. ssl on has been removed.

The syntax has been tested, nginx reloaded, the ports have been tested with nmap (both 80 and 443 are open).

When I curl -k (since the certificate is self-signed) 127.0.0.1 I get this message:

301 Moved Permanently nginx/1.14.0 (Ubuntu)

When I curl -k 127.0.0.1:443 I get this message:

400 The plain HTTP request was sent to HTTPS port 400 Bad Request The plain HTTP request was sent to HTTPS port nginx/1.14.0 (Ubuntu)

Could someone help me to understand what am I doing wrong? I'd be happy to provide more information. Thank you so much!!

Upvotes: 0

Views: 1343

Answers (1)

richardsefton
richardsefton

Reputation: 370

So here is an nginx config that is working for me.

upstream app {
    server app:8080;
}

server {
    listen 80;
    listen [::]:80;
    server_name webprojects-dev.co.uk;
    return 301 https://webprojects-dev.co.uk$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 http2;
    server_name webprojects-dev.co.uk;

    include /etc/nginx/common.conf;
    include /etc/nginx/ssl.conf;

    location / {
        proxy_pass http://app;
        include /etc/nginx/common_location.conf;
    }
}

In this instance nginx is running in a stack of docker containers networked with docker compose but that shouldnt have any bearing on how it works.

The upstream is the app container (and port) for a reverse proxy.

The first server block is forwarding on requests to https. As you can see the main difference between mine and yours is the server_name is the domain name and is also included in the return 301 statement.

The second server block is for https. Again server_name is a domain but other than that the only other difference I can see is I don't have ssl on the line listen [::]:443.

Disclaimer: Not an expert on nginx. I just hacked away till I had a reverse proxy config that works for me and now I just copy and paste it for everything.

Upvotes: 0

Related Questions