How to block access using the server IP and redirect non-www to www with SSL in 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

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;

        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/; # m$
    ssl_certificate_key /etc/letsencrypt/live/; #$
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

server {
    if ($host = {
        return 301;
    } # managed by Certbot
    if ($host = {
        return 301;
    } # managed by Certbot

    listen 80;
    return 444; # managed by Certbot


Kindly help me resolve this.

Thanks in advance!

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

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.

If you want to block the IP address that uses 443 port, just add listen to 443 and change the server_name with your IP address, so it looks like this:

server {
    listen 443;
    server_name your_ip_address;
    return 403;

Don’t forget to check the syntax if it is successful or not: sudo nginx -t

And reload your Nginx server: sudo systemctl reload nginx

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.


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

service nginx restart

Regards, KFSys