How to only allow www domains and prohibit naked domains through Nginx
In website management, we often hope that users can only use it withwww
domain name access, while for naked domain names (i.e. nowww
The 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 usewww
Visit the website and prohibit or redirect naked domain names.
Step 1: Configure Nginx to process www domain name
First, we are in Nginx forwww
Create 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/zhanmeng
and try to loador
document.
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's
return 444
instruction. 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 use
301
Redirect. In this way, all requests for naked domain names will be directed to the bandwww
domain name.
server { listen 80; server_name ; return 301 $request_uri; }
This way not only preserves the path requested by the user (e.g./about
Will 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 usewww
Domain 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!