Nginx http redirect to https

httpsnginx

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 the www. disappeared).

Second, your other server block is already handling http://www.example.pl.

Remove the listen 80; from the second server block, so that it only handles https connections. Use return 301 https://www.example.pl$request_uri; to perform the redirect to the correct scheme and server name.

For example:

server {
    listen 80;
    server_name example.pl *.example.pl;
    return 301 https://www.example.pl$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.pl;
    ...
}