Nginx HTTP to HTTPS – How to Fix HTTP Not Redirecting to HTTPS

dockernginx

NOTE: I asked this question previously on StackOverflow, didn't get any response.


Yes, this question has been asked multiple times and yes, I have gone through all the solutions, accepted or not. But still facing an issue.

I can access the website at https://example.in but Nginx is not redirecting http://example.in to https://example.in

I am running NGINX inside docker.

Nginx configurations are

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

        server_name example.in www.example.in;

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

server {
        listen 443 ssl;
        server_name example.in www.example.in;
        ssl_certificate /etc/nginx/certs/example.in.crt;
        ssl_certificate_key /etc/nginx/certs/example.in.key;

        location /static {
                alias /vol/web/;
        }

        location / {
                uwsgi_pass ${APP_HOST}:${APP_PORT};
                include /etc/nginx/uwsgi_params;
                client_max_body_size 10M;
        }
}

Dockerfile for Nginx is

FROM nginx:1.21.3
LABEL maintainer="example.in"

COPY ./default.conf.tpl /etc/nginx/default.conf.tpl
COPY ./uwsgi_params /etc/nginx/uwsgi_params
COPY ./data/certs/example.in.crt /etc/nginx/certs/
COPY ./data/certs/example.in.key /etc/nginx/certs/
COPY ./run.sh /run.sh

ENV LISTEN_PORT=8000
ENV APP_HOST=app
ENV APP_PORT=9000

RUN mkdir -p /vol/static && \
    chmod 755 /vol/static && \
    touch /etc/nginx/conf.d/default.conf && \
    chown nginx:nginx /etc/nginx/conf.d/default.conf && \
    chmod +x /run.sh && \
    chmod +r /etc/nginx/certs/example.in.crt && \
    chmod +r /etc/nginx/certs/example.in.key

VOLUME /vol/static

CMD ["/run.sh"]

docker-compose.yml

version: '3.9'

services:
  app:
    build:
      context: .
    restart: always
    volumes:
      - static-data:/vol/web
    environment:
      - ... (some environment variables)
    
  proxy:
    build:
      context: ./proxy
    restart: always
    depends_on:
      - app
    ports:
      - "80:8000"
      - "443:443"
    volumes:
      - static-data:/vol/web
      - ./data/certs:/etc/nginx/certs

volumes:
  static-data:

The app mentioned here is a Django web app serving the static files via Nginx.

I have never worked with Nginx before this.

Some more info that may be useful for debugging –

  1. docker container logs <nginx-container-id> don't show any logs for it trying to access on http.
  2. Checked with linux firewall, and port 80 is accessible.

PS: Somedays ago, I was facing another issue with Nginx config which was exact opposite of this. If you need some reference to that, please see this question. I was though able to find solution myself and shared it there itself.

Best Answer

You are mapping Port 80 to the port 8000 in your docker-compose.yml. Your requests never reach nginx.

ports:
  - "80:80"
  - "443:443"