Methods of payment Abuse

How to redirect from WWW to non-WW in Nginx

22.02.2022, 20:05


In order to optimize the site according to SEO rules, it must have one domain. A subdomain with www is considered a separate domain, in case it will be inaccessible, it will lead to the appearance of duplicate content. What does it mean? Duplicates - unwanted elements, often becoming the cause of a decrease in the position of the site in the search engines. That's why you should do a redirect from the domain www to without www. So in the beginning, the subdomain www was used in order to designate the server that he can not deploy a web server and placed the site. Now this is no longer necessary. In this article we will look at how to do a redirect from www to no www Nginx.

How to make redirect without WWW in NGINX

The simplest way to make a redirect in Nginx for www domain is to create a separate server section for it and redirect from there. For example:

server {
server_name www.losst.ru;
return 301 $scheme://losst.ru$request_uri;
}

In the case where you need to designate the handling of www and non-www in the same server section, you can use a condition and a regular expression. When the host variable has the letters www at the beginning, you should return a 301 response code and a link to which the user should be redirected:

if ($host ~* ^www.(.*)$) {
return 301 $scheme://$server_name$request_uri;
}

The code should be added to the server section of the site for which you want to configure the redirect. If you are using a LetsEncrypt SSL certificate, you will need to generate a validation for both the www domain and the non-www domain. The confirmation request should return a response, not a redirect. To do this, you can create a $need_redirect variable and then change its value with a few conditions:

set $need_redirect "0";
if ($host ~* ^www.(.*)$) {
set $need_redirect "1";
}
if ($request_uri ~* "well-known") {
set $need_redirect "0";
}
if ( $need_redirect ~ "1") {
return 301 https://$server_name$request_uri;

When the URL contains the word well-known, which is used in the domain validation request for an SSL certificate, the redirect will fail. Save the settings. Save the settings and restart Nginx:

nginx -s reload

Or:

sudo systemctl restart nginx

You can then test if the redirect works using curl:

curl -I www.losst.ru

The redirect will return, the Location field has a URL to redirect the user to. But if you try to access the URL from LetsEncrypt, there will be no redirect:

curl -I https://www.losst.ru/.well-known/acme-challenge/xxxxxxxxxxxxxxxxxxxxxxx

Everything works as expected. This is the end of the instruction.