Redirecting Traffic from www.domain.com to domain.com

April 1, 2019 327 views
Nginx Ghost Let's Encrypt

I’ve decided to use the one-click Ghost install on digitalocean, and I like how easy it has made the process. However, I am having an issue with my site. I want to redirect the www.domain.com to domain.com, but my config doesn’t seem to work.

I have Letsencrypt certs for my domain which is arsalan.io, and it works fine. It gives a cert error if you try www.arsalan.io, so since I don’t want people browsing to www, I’d rather just have it forwarded to arsalan.io. I’ve setup www as a CNAME that points to the main domain.

My NGINX config is as follows (/etc/nginx/sites-available/arsalan.io.conf):

server {
    listen 80;
    listen [::]:80;

    server_name arsalan.io;
    root /var/www/ghost/system/nginx-root;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;
        proxy_pass http://127.0.0.1:2368;

    }

    location ~ /.well-known {
        allow all;
    }

    client_max_body_size 50m;
}

I’ve tried modifying it so it looks like the following but it doesn’t redirect:

server_name arsalan.io www.arsalan.io;
redirect 301 https://arsalan.io$request_uri;

I haven’t modified arsalan.io-ssl.conf

1 Answer

Because you want to redirect a request from www.arsalan.io to arsalan.io you want to create a new server directive that is listening for connections on just www.arsalan.io and then add the redirect.

So you would need to update your configuration with the following:

server {
    server_name www.arsalan.io;
    return 301 $scheme://arsalan.io$request_uri;
}

In the snippet that you posted you had both server_names present, which may have been causing the issue.

You can find a more detailed write here:
How to redirect with Nginx

by Mitchell Anicas
This tutorial will show you how to redirect a www URL to non-www, e.g. `www.example.com` to `example.com`, with Nginx on CentOS 7. We will also show you how to redirect in the other direction, from a non-www URL to www.
Have another answer? Share your knowledge.