I have my nginx config and I am trying to redirect from a non www. version of the site to the www. version.

server {
listen       80;
server_name  *.example.com example.com;
rewrite ^ https://www.example.com$request_uri permanent;
server {
 listen      443 ssl;
 server_name www.example.com;
 ssl_certificate      /etc/ssl/www.example.com/www.example.com.crt;
 ssl_certificate_key  /etc/ssl/www.example.com/www.example.com.key;


When I do the curl -I I get a 301 permanently moved Location: https://example.com

  • If you want it to redirect for https, you need to have a redirect on the https (hint: port 80 isn't it). – yoonix May 23 '16 at 17:59

You actually have two servers configured, one for regular (http) access and another for secure access (https)

In a server section for a server that you are going to redirect non-www request to www you need to add the following at the beginniging:

set $primary_domain www.yourdomian.com;
if ($host != $primary_domain) {
    rewrite  ^(.*)$ http://$primary_domain$1  permanent;

This will actually redirect all hosts configured in this server to www version, not only empty sub domain. Make sure to remove a section starting with return is such a case as it would make another redirect and you could end up in an endless loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.