The server names are an important part of your nginx configuration. If you server multiple domains/sub-domains from a server with a single public IP, the server_name
directive tells nginx what server should respond to a request. If there is no matching server name, nginx will next look for a default server that, if present, act as some sort of 'catch all' server.
Here's a configuration example for http -> https redirect where you can also see how to name servers correctly without getting errors.
/etc/nginx/sites-available/www.example.com.vhost
# This server will redirect all http -> https
server {
# Listen for both IPv4 and IPv6 requests.
listen 80;
listen [::]:80;
server_name www.example.com example.com;
# This section assuming you're using Let's Encrypt / certbot
location ^~ /.well-known/acme-challenge/ {
default_type "text/plain";
root /path/to/your/document/root
}
location = /.well-known/acme-challenge/ {
return 404;
}
# Here's where your 301 permanent redirect to the https:/www version happens.
return 301 https://www.example.com$request_uri;
}
# This server will redirect all https requests without www to the version with www
server {
# Listen for both IPv4 and IPv6 requests and activate http2.
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
ssl on;
# Paths to certificates assuming you're using Let's Encrypt / certbot
ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
# There's much more directives you should fine tune for https, but that's another task.
# Here's where your 301 permanent redirect to the https://www version happens.
return 301 https://www.example.com$request_uri;
}
# This server will actually server your https content.
server {
# Listen for both IPv4 and IPv6 requests and activate http2.
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;
ssl on;
# Paths to certificates assuming you're using let's encrypt / certbot
ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
# There's much more directives you should fine tune for https, but that's another task.
####
#
# Your server directives go here.
#
####
}