Nginx Redirects For "non-www" Sub-domains To "www"


Introduction

When you visit https://vultr.com, you’ll notice it automatically forwards you to its “www” subdomain http://www.vultr.com. This writeup shows you how to setup Nginx to redirect a non-www sub-domain to a “www” one, and vice-versa.

Pre-requisites

  • You have a Vultr Linux instance running Nginx.
  • Your have domain name (e.g example.com) whose DNS A records for “@” and “www” are pointing to the IP of your Vultr machine above.

Setup to redirect “non-www” to “www”

Method 1: For a single domain

Add an additional server block to your vhost setting so it looks similar to below:

server {    listen 80;    server_name example.com;    return 301 $scheme://www.example.com$request_uri;}server {    listen 80;    server_name www.example.com;    #other site settings go here (e.g. logs, site root)}
Method 2: For all domains

Add below snippet within the http directive in your nginx.conf file (usually located in /etc/nginx in Ubuntu/Debian systems)

server {    server_name "~^(?!www/.).*" ;    return 301 $scheme://www.$host$request_uri;}

Setup to redirect “www” to “non-www”

Method 1: For a single domain

Add an additional server block to your vhost setting so it looks similar to below:

server {    listen 80;    server_name www.example.com;    return 301 $scheme://example.com$request_uri;}server {    listen 80;    server_name example.com;    #other site settings go here (e.g. logs, site root)}
Method 2: For all domains

Add below snippet within the http directive in your nginx.conf file (usually located in /etc/nginx in Ubuntu/Debian systems)

server {    server_name "~^www/.(.*)$" ;    return 301 $scheme://$1$request_uri ;}

Written by Lami Adabonyan

Want to contribute?

You could earn up to $300 by adding new articles

Submit your article
Suggest an update
Request an article

No comments

Powered by Blogger.