Actually, I am an apache user and very new to nginx so please tell me where to save these codes under which directory and with what file name and file type?
As there is nothing like .htaccess for nginx

The single domain config will add a redirection only to a specific domain that you have mentioned in the configuration. Hence, the config in the post has example.com domain which you can replace with the specific single domain.

The All domains config will add it to all the domains for which requests are made on the server.

These config will be added to your Nginx configuration file. It will typically be under

Its not working for me. I tried many options of putting server {
server_name “~^(?!www\.).*” ;
return 301 $scheme://www.$host$request_uri;
}
but nothing works for me.
Here is my sites available file http://pastebin.com/aTy9xtca

Thanks Rahul but nothing works for me:(. I added your line and same, also I added this line server {
server_name “~^(?!www\.).*” ;
return 301 $scheme://www.$host$request_uri;
} also in nginx.conf file so also isnt working (basically I try all these lines on different positions and same again. when without www it shows all ok when with www Server not found. Maybe problem in this that my http://www.mysite.com was never reachable? Maybe I should do something to bring this www to live site and then to redirect. ?

Thanks Rahul but not success. I added this line and I was trying with different lines different positions and even different files f.e. ngnix.conf (where I should exactly add this line?)
I think that problem can be because my www never was reachable . Maybe I should do something to make it reachable and to point to my site and then to redirect?

Sorry for delayed reply. At this point, I won’t be able to debug further via comments only.

You need to make sure:

1. For all desired domains, DNS lookup reaches to your server’s IP.
2. Nginx server_name block as wildcard e.g. *.example.com and/or listening by default on that IP. “listening by default” is recommended for domain-mapping.
3. You need to use rules like I posted in previous comment “if server_name starts with www, regex to fetch domain/hostname without www and redirect to it”

There are few more ways and tricks but its not possible for me to debug it like this. You can give it a try, or may hire somebody as a last resort.

Thanks Rahul. You idea brought me to solve this issue with redirection.
Only I don’t know if I did it right way (to not have further problems).
What I did: I added 2 CNAME records in my dns:
CNAME * @
CNAME www @
and also your line for this article and all is redirecting now properly.
What o you think is this all correct way as I newer heard for www line before.
Cheers!