Configuring nginx to allow only https traffic

2k views Asked by At

I am super new to linux environment, and trying to configure a vps server to only allow https requests. I have read nginx documentation and tried various rewrite and return statements, changing server blocks etc. But what I have achieved so far, site serves on http and https both with following config.

What I want to achieve is to configure this subdomain admin.example.com to serve only https requests.

I am editing the config at this location: /etc/nginx/sites-available/default

server {
    listen 80;

    server_name admin.example.com;


    #return 301 https://admin.example.com$request_uri;


    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/admin.byrides.com/fullchain.pem; # man                                                                                                                                                             aged by Certbot
    ssl_certificate_key /etc/letsencrypt/live/admin.byrides.com/privkey.pem; # m                                                                                                                                                             anaged by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

 }
1

There are 1 answers

5
hcheung On

You will need to setup two server directives, one for port 80 which will redirect the traffic to port 443.

server {
    listen 80;
    server_name admin.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    ssl on;

    ssl_certificate /etc/letsencrypt/live/admin.byrides.com/fullchain.pem; # man                                                                                                                                                           aged by Certbot
    ssl_certificate_key /etc/letsencrypt/live/admin.byrides.com/privkey.pem; # m                                                                                                                                                             anaged by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
    }
}