TheLearner
TheLearner

Reputation: 2863

NGINX configurations not redirecting non-www to www

I have a NodeJS app running on port 3000 on an Ubuntu 16 server hosted on an AWS EC2 instance. I want NGINX to redirect each of the following addresses to https://www.example.com:

  1. http://example.com
  2. http://www.example.com
  3. https://example.com

To that end, I have configured my /etc/nginx/sites-available/default file as follows:

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    location / {
        # Redirect any http requests to https
        return 301 https://www.$server_name$request_uri;
     }
     location ~* \.(?:ico|svg|woff|woff2|ttf|otf|css|js|gif|jpe?g|png)$ {
        proxy_pass http://127.0.0.1:3000;
        expires 30d;
        add_header Pragma public;
        add_header Cache-Control "public";
     }
}

# Settings for a TLS enabled server
server {
        listen 443 ssl http2;
        listen [::]:443 ssl;
        server_name  www.example.com;

        ssl_certificate "/etc/letsencrypt/live/example.com/fullchain.pem";
        ssl_certificate_key "/etc/letsencrypt/live/example.com/privkey.pem";

        # Automatically route HTTP to HTTPS
        add_header Strict-Transport-Security "max-age=31536000";

        include /etc/nginx/default.d/*.conf;

        location / {
            proxy_pass http://127.0.0.1:3000;
       }
   }

However, this only seems to be working partially:

  1. http://example.com -> goes to https://example.com instead of https://www.example.com
  2. http://www.example.com -> goes to https://example.com instead of https://www.example.com
  3. https://example.com -> goes to https://example.com instead of https://www.example.com
  4. https://www.example.com -> works fine

Any suggestions?

Upvotes: 0

Views: 39

Answers (1)

IVO GELOV
IVO GELOV

Reputation: 14259

You should have a server block for each case which you want to redirect:

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

# Settings for a TLS enabled server
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name  example.com;
    return 301 https://www.example.com$request_uri;
}
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name  www.example.com;

    ssl_certificate "/etc/letsencrypt/live/example.com/fullchain.pem";
    ssl_certificate_key "/etc/letsencrypt/live/example.com/privkey.pem";

    # Automatically route HTTP to HTTPS
    add_header Strict-Transport-Security "max-age=31536000";

    include /etc/nginx/default.d/*.conf;

    location / {
        proxy_pass http://127.0.0.1:3000;
   }
}

Upvotes: 1

Related Questions