Nginx redirects. Http to https and www to non-www

January 26, 2015 6.7k views

I need some help with my nginx config so all my http traffic goes to https and also www changes to non-www. My server is running ubuntu 14.04 and nginx. Also my site has cloudflare activated. My goal is that everyone goes to this url https://nicholaschedid.com because my cert if for nicholaschedid.com

here is my sites-available .conf file

server {
        server_name nicholaschedid.com;
        return 301 https://$server_name$request_uri;
}

server {
        listen 443 ssl;
        listen [::]:443 ssl;
        server_name nicholaschedid.com;

        ssl on;
        ssl_certificate /etc/nginx/ssl/bundle.crt;
        ssl_certificate_key /home/worker/nicholaschedid.com.key;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL;

        root /var/www/nicholaschedid.com/html/_site;
        index index.php index.html index.htm;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
                # Uncomment to enable naxsi on this location

                [. . .]

So far

I tried so many different configuration but none worked, from both google and here.

2 comments
3 Answers

Hello!
I this should work :)
Feel free to tell me if you don't understand something of this configuration file!
I prefer using rewrites for stuff like that, but there's not a really big difference - in this case -between using rewrite or return.

server {
    listen 80;

    server_name nicholaschedid.com www.nicholaschedid.com;
    rewrite ^/(.*) https://nicholaschedid.com/$1 permanent;
}

server {
    listen 443 ssl;

    server_name www.nicholaschedid.com;
    ssl_certificate /etc/nginx/ssl/bundle.crt;
    ssl_certificate_key /home/worker/nicholaschedid.com.key;

    rewrite ^/(.*) https://nicholaschedid.com/$1 permanent;
}

server {
    listen 443 ssl;

    server_name nicholaschedid.com;


    ssl_certificate /etc/nginx/ssl/bundle.crt;
    ssl_certificate_key /home/worker/nicholaschedid.com.key;

    [ stuff goes here ]
}

Have a nice day,
Alfio.

Try something like this:
Create a new conf file like redirec.conf and add:

server {
    listen      80;
    server_name www.domain.com; #or server_name .domain.com; for wildcard subdomains

    location / {
        if ($host !~* ^(www)) {
          rewrite ^/(.*)$ https://www.domain.com/$1 permanent;
        }
    }
}

@nicholasfc Mhh, that's strange.
Can you try to temporally disable Cloudflare?

Have another answer? Share your knowledge.