redirect wildcard subdomains to https (nginx)

I've got a wildcard ssl certification and I'm trying to redirect all non-ssl traffic to ssl. Currently I'm using the following for redirection the non-subdomainded url which is working fine.

server {
listen      80;
server_name mydomain.com;

#Rewrite all nonssl requests to ssl.
rewrite     ^ https://$server_name$request_uri? permanent;
}

when I do the same thing for *.mydomain.com it logically redirects to

https://%2A.mydomain.com/

How do you redirect all subdomains to their https equivalent?


That's all...

server {
    listen      80;
    server_name *.mydomain.com;

     #Rewrite all nonssl requests to ssl.
     return 301 https://$host$request_uri;
}

The NGINX official documentation encourages to use the return directive instead of using rewrite directive for effecting redirection. This is so, as the request being rewritten is not meant for that server, but it still gets processed in that server block. So redirects are correctly done with a return directive instead, as all processing is stopped and a response is sent immediately. NGINX discourages rewrite for redirection here: http://nginx.org/en/docs/http/converting_rewrite_rules.html

The syntax for return directive is: return code URL; As you were originally doing a permanent rewrite, so accordingly you can use 301 as the code to respond with, indicating it is a permanent redirect. Your https address will be passed in the url section. Reference: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#return

So your correct configuration would be

server {
listen      80;
server_name *.mydomain.com;

#Redirect all nonssl requests to ssl.
return 301 https://$server_name$request_uri;
}

This would probably let you redirect correctly to your ssl domain, with a wildcard server block. You can also try the underscore generic server name '_' or $host as suggested in the comment above. Let us know!