Question

How to block access using the server IP and redirect non-www to www with SSL in Nginx?

Posted August 6, 2020 153 views
Nginx

Hello all!

  1. I have configured a domain using an Ubuntu 18.04 DO droplet.
  2. I have successfully installed Nginx.
  3. I have followed and successfully installed SSL using the tutorial here digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04

Q1. How to block access using the server IP and return error 444 on SSL? As you can see in my configuration it blocks at port 80.

Q2. I have redirected non-www to www, is that correct?

The configuration for my webserver is:

server {
        root /var/www/html;
        index index.php index.html index.htm index.nginx-debian.html;
        server_name example.com www.example.com;

        location / {
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        }

        location ~ /\.(?!well-known) {
                deny all;
                }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # m$
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; #$
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = www.example.com) {
        return 301 https://www.example.com;
    } # managed by Certbot

    if ($host = example.com) {
        return 301 https://www.example.com;
    } # managed by Certbot

    listen 80;
    server_name example.com www.example.com;
    return 444; # managed by Certbot

}

Kindly help me resolve this.

Thanks in advance!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
1 answer

Hi @sagarsharmaweb,

You can add this server block to your configuration.

server {
    listen      80 default_server;
    server_name "";
    return      444;
}

You need to specify “defaultserver” parameter so that all non available server requests goes to this server block which throws 444 error. The “defaultserver” parameter cannot be present in any other server block.

444 : CONNECTION CLOSED WITHOUT RESPONSE

After you make the changes, don’t forget to restart nginx

service nginx restart

Regards,
KFSys

Submit an Answer