Nginx force ssl http

I am struggling on how to force SSL on my site (nginx). I would like to force redirect from both http://www.example.com "and" http://example.com "to" https://example.com "(without any www).

The code that I have written at the moment can catch " http://www.example.com ", but does not break " http://example.com ", it seems like an endless redirection loop. I am sure this has something to do with "server_name". I tried to swap it down inside the "server {...}" brackets and stuff, but it still doesn't behave as we would like.

Here is my nginx conf

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

server {

    server_name     example.com;

    root            /var/www/example.com;
    index index.html index.php index.htm;

    location / {
        include         /etc/nginx/conf/fastcgi_params;
        fastcgi_pass    unix:/var/run/php5-fpm.sock;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME $document_root/$fastcgi_script_name;

    }

    location ~ /\.ht {
        deny            all;
    }

}


server {

    #listen 443 spdy default deferred;
    ssl                         on;
    ssl_certificate_key         /etc/myssl/www.example.com.key;
    ssl_certificate             /etc/myssl/www.example.com.chained.crt;
    ssl_protocols               TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers                 'ECDHE-RSA-AES128-[...]';
    ssl_prefer_server_ciphers   on;
    ssl_dhparam                 /usr/share/myssl/dhparams/dh2048-group14.pem;
    ssl_session_timeout         5m;
    ssl_session_cache           shared:SSL:5m;
    add_header                  Strict-Transport-Security max-age=15768000;

}
0
1

server, , :

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

server {
    listen          443 ssl spdy; 
    server_name     www.example.com;
    ssl_certificate_key         /etc/myssl/www.example.com.key;
    ssl_certificate             /etc/myssl/www.example.com.chained.crt;
    [other ssl_* directives, as required]
    return 301      https://example.com$request_uri;
}

server {
    listen          443 ssl spdy; 
    server_name     example.com;
    ssl_certificate_key         /etc/myssl/www.example.com.key;
    ssl_certificate             /etc/myssl/www.example.com.chained.crt;
    [other ssl_* directives, as required]
    [remaining example.com configuration here]
}

HTTP ( 80) http://www.example.com http://example.com https://example.com. https://www.example.com https://example.com. SSL/SPDY https://example.com.

HTTPS , , -, .

: server, , , https://www.example.com , , SSL- ( www.example.com example.com). , DNS.

, (, /etc/nginx/conf.d /etc/nginx/sites-enabled, ).

: .

+2

All Articles