Peter
Peter

Reputation: 11890

Redirecting in nginx results in errors

Environment: Ubuntu 18.04, nginx, WordPress

WordPress is running fine at https://www.example.org. In addition, the following rule is defined to direct http to https:

server {
  if ($host = www.example.org) {
    return 301 https://$host$request_uri;
  } # managed by Certbot


  listen 80;
  server_name www.example.org;
  return 404; # managed by Certbot
}

With this, a user's request to http://www.example.org automatically gets redirected to https://www.example.org.

Now, I am trying to define a rule such that https://example.org can also be redirected to https://www.example.org.

Here is my new nginx rule:

server {
  listen 443 ssl;

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

However, this seems results in breaking the whole site. Even https://www.example.org, that was working fine earlier, gives an error that "this site can't be reached."

This is the last error from nginx error.log:

no "ssl_certificate" is defined in server listening on SSL port while SSL handshaking, client: blah, server: 0.0.0.0:443

To recap,

https://www.example.org works fine
http://www.example.org properly gets redirected to https://www.example.com
https://example.org does not work. It should also have been redirected to https://www.example.org

Can someone please tell me what is it that I am doing wrong? Regards.

Upvotes: 0

Views: 91

Answers (1)

EternalHour
EternalHour

Reputation: 8621

You haven't specified if you need all URIs to redirect, but here are several options. Make sure you are restarting the nginx service after these changes.

Specific URIs

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

All URIs

server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

Upvotes: 1

Related Questions