Nginx Force (Redirect) WWW.Domain.COM To Domain.COM
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
retu directive with a 301 status code to redirect requests to the non-www version. Here’s an example configuration:server {
n listen 80;
n server_name www.domain.com domain.com;
n return 301 $scheme://domain.com$request_uri;
n}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
retu 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 reloadNow, 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.
