nginx / ssl: Always redirect to one of two https subdomains [duplicate]
First of all you should understand that you can't make a "transparent" https redirection from https://something.example.com
to https://www.example.com
if your SSL certificate doesn't support something.example.com
domain. It will show Your connection is not secure
error or similar, when accessed. However, you should be able to redirect from http://*.example.com
to https://www.example.com
without any troubles. To do that, add the following on top of your nginx.conf
:
server {
listen 80;
default_server;
server_name _;
return 301 https://www.example.com$request_uri;
}
It should redirect any request to your IP to https://www.example.com
Then we add configurations for specific redirects. This one for http://en.example.com
-> https://en.example.com
:
server {
listen 80;
server_name en.example.com;
return 301 https://en.example.com$request_uri;
}
This one for http://www.example.com
-> https://www.example.com
:
server {
listen 80;
server_name www.example.com;
return 301 https://www.example.com$request_uri;
}
And finally, we add configuration for "real" domains that should serve desired content via SSL. This one for http://www.example.com
:
server {
listen 443 ssl;
ssl_certificate /etc/ssl/www.example.com.crt;
ssl_certificate_key /etc/ssl/www.example.com.key;
server_name www.example.com;
<your www.example.com server config here>
...
</your www.example.com server config here>
}
This one for http://en.example.com
:
server {
listen 443 ssl;
ssl_certificate /etc/ssl/en.example.com.crt;
ssl_certificate_key /etc/ssl/en.example.com.key;
server_name en.example.com;
<your en.example.com server config here>
...
</your en.example.com server config here>
}