nginx: Exclude subdomains from being SSL-encrypted

Can you exclude all other subdomains from being encrypted if the main site url is using SSL?

server {
    listen 80;
    listen [::]:80;

    server_name .example.com;
    return 301 https://$host$request_uri;
}
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    ## ssl stuff

    server_name www.example.com;
    return 301 https://example.com$request_uri;
}
server {
    listen 443 ssl default_server http2;
    listen [::]:443 ssl http2;
    server_name example.com;
    root /home/forge/example.com/public;
    index index.html index.htm index.php;
    charset utf-8;   
}

Solution 1:

Define a more specific server, that will be used in place of the one you have.

server {
  listen 80;
  server_name subdomain1.example.com; # add others if you like
  root /home/forge/example.com/public/subdomain; # check this
  index index.html index.htm index.php;
}

As ceejay noted in comments there's no redirect included in the config you included, so something else is going on.


To round it up, the more specific `server_name` gets served and therefore no `301` redirect is made. Taken from [here][1].
  1. exact name
  2. longest wildcard name starting with an asterisk, e.g. “*.example.org”
  3. longest wildcard name ending with an asterisk, e.g. “mail.*”
  4. first matching regular expression (in order of appearance in a configuration file)