Reputation: 3089
I have the following server names that I want to be accessible, on https:
example.com
test.example.com
api.example.com
api.test.example.com
# And I might add more, all on example.com of course
# ...
I want to redirect all http
, http://www
and https://www
to https://non-www
Like:
http://example.com => https://example.com
http://test.example.com => https://test.example.com
http://api.example.com => https://api.example.com
http://api.test.example.com => https://api.test.example.com
http://www.example.com => https://example.com
http://www.test.example.com => https://test.example.com
http://www.api.example.com => https://api.example.com
http://www.api.test.example.com => https://api.test.example.com
https://www.example.com => https://example.com
https://www.test.example.com => https://test.example.com
https://www.api.example.com => https://api.example.com
https://www.api.test.example.com => https://api.test.example.com
Looking at a some simple example I've found online, I tried the following:
server {
listen 80;
server_name example.com test.example.com www.example.com www.test.example.com api.example.com api.test.example.com www.api.example.com www.api.test.example.com;
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443;
server_name www.example.com www.test.example.com www.api.example.com www.api.test.example.com;
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443;
server_name example.com test.example.com api.example.com api.test.example.com;
#
# The rest of the config that that follows is indeed for the names
# that I want to redirect everything to
# ...
}
I thought that $host
means the part of the url before /
and without www
.
Like if I access www.api.test.example.com
then $host would be api.test.example.com
. And so on.
But, after noticing the way it's behaving and checking out Nginx variables, it seems I thought wrong. Although it doesn't explain very clearly and doesn't offer examples, nor do they say what variable to use in order to get the full domain (subdomain included) without www.
Upvotes: 2
Views: 395
Reputation: 49672
There is more than one way to do this, but if this server only handles subdomains of example.com
, you can simplify by using regular expressions and default servers, rather than specifying long lists to the server_name
directive.
For example:
server {
listen 80;
listen 443 ssl;
server_name ~^www\.(?<domain>.+)$;
return 301 https://$domain$request_uri;
}
server {
listen 80 default_server;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl default_server;
...
}
The first server
block only matches hostnames that begin with www.
. The second server block matches everything else using http
. The third server
block matches everything else using https
.
It is assumed that this server has a wildcard certificate, common to all subdomains. See this document for more.
Upvotes: 2