Your second example will work for any requests going to http://example.com, however remember that www.example.com and example.com are different so if you needed to redirect for anything at example.com you could do
server {
listen 80;
server_name *.example.com;
return 301 https://$server_name$request_uri;
}
or else redirect for each host, i.e.
server {
listen 80;
server_name www.example.com example.com images.example.com cdn.example.com;
return 301 https://$server_name$request_uri;
}
Make sure you both test the config via nginx -t
and reload the configuration when you make changes via a nginx reload. You can test what your getting via either live http headers or curl
The below output is what I see when trying a http header request to a domain that we direct to https with the exact server block above.
$ curl -I -L http://host.domain.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.6.2
Date: Mon, 06 Apr 2015 03:26:39 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: https://host.domain.com/
HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Mon, 06 Apr 2015 03:26:41 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.22
Set-Cookie: PHPSESSID=dca72682392e7ac96d4b7703ea7a1eb1; path=/; domain=domain.com; secure; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPSESSID=c910822f8007fe8c0424715a24aa4728; path=/; domain=domain.com; secure; HttpOnly