I have config like this:
server {
listen 80;
server_name example.pl *.example.pl;
rewrite ^/(.*)$ http://www.example.pl/$1 permanent;
}
server {
listen 80;
listen 443 ssl;
ssl on;
ssl_certificate /opt/nginx/ssl/server.pem;
ssl_certificate_key /opt/nginx/ssl/server.key;
server_name www.example.pl;
root /var/www/example/public/; # <--- be sure to point to 'public'!
}
So now every subdomain like xx234.example.pl is rewrite to http://www.example.pl
Now I try to set https. https://www.example.pl works ok, but I can't redirect traffic from http to https.
When I do this:
server {
listen 80;
server_name example.pl *.example.pl;
#rewrite ^/(.*)$ http://www.example.pl/$1 permanent;
return 301 https://$server_name$request_uri;
}
It's redirect but to https://example.pl without www. How to redirect it correctly. I want to have that same configuration but with https.
This also doesn't work:
server {
listen 80;
server_name example.pl *.example.pl;
rewrite ^/(.*)$ https://www.example.pl/$1 permanent;
}
Best Answer
You have two issues:
First you switched from using
www.example.pl
to$server_name
(which is why thewww.
disappeared).Second, your other server block is already handling
http://www.example.pl
.Remove the
listen 80;
from the secondserver
block, so that it only handleshttps
connections. Usereturn 301 https://www.example.pl$request_uri;
to perform the redirect to the correct scheme and server name.For example: