C314e11a169e971a034db92b3f91be6f5a50bfc0
By:
maszd

nginx https redirect www to non-www

April 6, 2017 1k views
Nginx CentOS

Hi i was config my nginx block to redirect all www to non-www, this is my config:

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

server {
    listen       443 ssl http2;
    server_name  mysite.com;
    root   /usr/share/nginx/html;

    ssl on;
    ssl_certificate /ssl/ssl-bundle.crt;
    ssl_certificate_key /ssl/mysite.key;
    ssl_session_cache shared:SSL:20m;
    ssl_session_timeout 10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:!DSS;
    ssl_buffer_size 8k;
    ssl_session_tickets off;

    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /ssl/ssl-trusted.crt;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 10s;

    #add_header X-Content-Type-Options "nosniff";

    location / {
        index index.php index.html index.htm;
    try_files $uri $uri/ /index.php?$uri&$args;
    }

    location /internal_data/ {
        internal;
        allow 127.0.0.1;
        deny all;
        }

        location /library/ {
        internal;
        allow 127.0.0.1;
        deny all;
        }

    location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include fastcgi_params;
    }

    location ~* \.(?:ico|css|gif|jpe?g|js|png|svg|svgz|swf)(\?.+)?$ {
        access_log              off;
        log_not_found           off;
        expires                 1y;
    }

location ~ \.(jpe?g|png|gif)$ {
     valid_referers none blocked mysite.com *.mysite.com;
     if ($invalid_referer) {
        return   403;
        }
    }
}

working fine just for non-www to https but not work from www to non-www,
this is result from curl -I http://www.mysite.com :

curl: (6) Couldn't resolve host 'www.mysite.com'

is there any iam miss?
thank you.

1 Answer
dpolyakov April 6, 2017
Accepted Answer

Check your DNS settings.
You must have CNAME or A entry "www".

www A   _your_droplet_ip_

or

www CNAME   domain.com
Have another answer? Share your knowledge.