Nginx Configuration for Domain-Only Web Access

This post explains how to configure Nginx so a website is accessible only by domain, not by IP.

Jun 2, 2018 · 1 min read · 143 Words · -Views -Comments · Programming
Deployment Operations 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

After setting up DNS, we achieved domain access to the web site. But the server IP was still visible, so users could access the site via IP. This creates two problems:

  1. If users access via IP and the server location changes, the IP changes and access fails.
  2. If someone maliciously points their own domain to our IP, they can also access the site. So we should disable IP access and only allow specific domains.

Specific configuration

Below is my Nginx configuration for a site https://tool.alan.me.

Configure a specific domain

server {
       listen       443 ssl;
       server_name  tool.alanhe.me;

        ssl on;
        ssl_certificate "/etc/nginx/ssl/fullchain.cer";
        ssl_certificate_key "/etc/nginx/ssl/tool.alanhe.me.key";
      ...  
  }

Add default service configuration

 server {
        listen 443 default_server ssl;
        server_name _;
        ssl on;
        ssl_certificate      /etc/nginx/ssl/fullchain.cer;
        ssl_certificate_key  /etc/nginx/ssl/tool.alanhe.me.key;
        return       403;
}

After configuration, restart Nginx: nginx -s reload.

Effect

When accessing via IP:

When accessing via the specified domain:

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover