To force a redirect from www.domain.com to domain.com using Nginx, you can add a server block to your Nginx configuration file with a server_name directive that includes both the www and non-www versions of your domain name, and a return directive with a 301 status code to redirect requests to the non-www version. Here’s an example configuration:
server {
listen 80;
server_name www.domain.com domain.com;
return 301 $scheme://domain.com$request_uri;
}
In this example, we’re listening on port 80 and setting the server_name directive to include both the www and non-www versions of the domain name. The return directive with a 301 status code will redirect requests to the non-www version of the domain, preserving the requested URI.
After adding this configuration, reload Nginx to apply the changes:
sudo service nginx reload
Now, when a user tries to access your website using the www version of your domain name, they will be automatically redirected to the non-www version.