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 ;
}
Link - 淘实惠-使用采购网站
This article was created by DieDie
This work is licensed under a Creative Commons Attribution 4.0 International License.
This article source Nginx Redirects For "non-www" Sub-domains To "www"
Last Modified Jan 12, 2019 at 12:55 am