HTTP to HTTPS Using Nginx

Hello,

I've configured HTTP to HTTPS redirect in my /etc/nginx/sites-available/default file. Its as below:

server {

listen 80 default_server;

listen [::]:80 default_server;

server_name example.com http://www.example.com;

return 301 https://$servername$requesturi;

}

server {

SSL configuration

listen 443 ssl http2 default_server;

listen [::]:443 ssl http2 default_server;

include snippets/ssl-example.com.conf;

include snippets/ssl-params.conf;

. . .

My problem is that everytime I try to go to "www.example.com" it redirects to "https://example.com". I would like it to redirect to "https://www.example.com". What am I doing wrong in the default file?

Thank you for your help!

1 Reply

Assuming you want both http://example.com and http://www.example.com to be redirected to https://www.example.com, try this instead:

server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;

You should probably put a server_name line inside the https server block as well.

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct