How can I redirect non-www to www in https NGINX How can I redirect non-www to www in https NGINX nginx nginx

How can I redirect non-www to www in https NGINX


Just create a server for non-www requests, for example:

# redirect http to httpsserver {    listen 80;    server_name www.example.com example.com;    return 301 https://www.example.com$request_uri;} # redirect http://example.com to https://www.example.comserver {    listen 443 ssl;    server_name example.com;    # ssl ...    return 301 https://www.example.com$request_uri;}# https://www.example.comserver {    listen 443 ssl;    server_name www.example.com;    # ssl ...}

The DNS records for example.com and www.example.com should be pointing to your Nginx server


Quick instruction for redirect and also for ssl

Don't write all conf all your sites in one file nginx.conf. Separate these. You have two folders for it /etc/nginx/sites-available/ and /etc/nginx/sites-enabled/

Add file for your site for example /etc/nginx/sites-available/exampleMake link ln -s /etc/nginx/sites-enabled/example

To this conf file paste text below:

server {  listen 80;  server_name example.com www.cova.company;  return 301 https://www.example.company$request_uri;}server {  listen 443 ssl;  server_name www.example.com;  ssl_stapling on;  ssl on;  ssl_certificate /etc/letsencrypt/live/www.site.com/fullchain.pem;       ssl_certificate_key /etc/letsencrypt/live/www.site.com/privkey.pem;  # your location there a}

In you nginx.conf ypu already have row include /etc/nginx/sites-enabled/*; it means automatically take all of their sites configs from folder sites-enabled

After it check syntax with command nginx -t and reload your nginx with command systemctl reload nginx

And after all off this who call your site via http://example.com or https://example.com will be redirected to https://www.example.com