SoFunction
Updated on 2025-03-03

Nginx only allows www domain name access and prohibits naked domain name access

How to only allow www domains and prohibit naked domains through Nginx

In website management, we often hope that users can only use it withwwwdomain name access, while for naked domain names (i.e. nowwwThe prefixed domain name prohibits access or redirection. This can be done by modifying the server configuration of Nginx (or Tengine). This article will introduce how to configure Nginx so that users can only usewwwVisit the website and prohibit or redirect naked domain names.

Step 1: Configure Nginx to process www domain name

First, we are in Nginx forwwwCreate a virtual host in the domain name to ensure that all passThe requests all point to the correct directory of the website. The specific configuration is as follows:

server {
    listen 80;
    server_name ;
    root /var/www/test;
    index  ;
    location / {
        try_files $uri $uri/ =404;
    }
}

This configuration tells Nginx that allThe request will point to the website root directory/var/www/zhanmengand try to loadordocument.

Step 2: Disable naked domain access

In order to prohibit users from passing naked domain namesAccess, we can create a standalone virtual host and use Nginx'sreturn 444instruction. This will cause Nginx to close the connection immediately without returning anything, thus prohibiting access.

server {
    listen 80;
    server_name ;
    return 444;
}

This method is very direct, users try to accessYou will see a prompt that the connection is rejected.

Step 3: Redirect the naked domain name to the www domain name (optional)

If you wish to visitUsers are automatically redirected to, you can modify the configuration to use301Redirect. In this way, all requests for naked domain names will be directed to the bandwwwdomain name.

server {
    listen 80;
    server_name ;
    return 301 $request_uri;
}

This way not only preserves the path requested by the user (e.g./aboutWill be redirected to/about) and is also more SEO-friendly.

Step 4: Restart the Nginx application configuration

After completing the configuration, remember to restart the Nginx server to make the changes take effect:

sudo systemctl restart nginx

Summarize

By modifying the Nginx configuration, we can easily achieve that users can only usewwwDomain access, while access is prohibited or automatically redirected to the naked domain name directlywww. This not only improves the brand unity of the website, but also improves user experience and SEO results.

This is the article about how to only allow www domain names through Nginx and prohibit access to naked domain names. For more related content for Nginx www domain names, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!