0

I have the following nginx conf file, everything I want is working except http traffic redirecting to https. when I add server_name example.com to the (first) server block that redirects http to https, I get a redirect loop error in the browser. What am I doing wrong. How to redirect http traffic to https without redirect loop, while preserving www redirect to the root domain

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    rewrite ^(.*) https://example.com$1 permanent;
 }

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

 server {
    server_name example.com;
    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    ssl_certificate /root/cert_chain.crt;
    ssl_certificate_key /root/example.com.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
            expires 30d;
            add_header Pragma public;
            add_header Cache-Control "public";
    }

    location / {
        try_files $uri $uri/ =404;
    }


    location /balcony-covers/ {
            return 301 $scheme://$host/balcony-screens/;
    }

    error_page 404 /404/;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

1 Answer 1

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

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

and then config the SSL one with following method.

server {
    listen      443;
    server_name www.example.com;

    ssl on;
    ssl_certificate     /opt/nginx/example.com/certs/example.ca-bundle;
    ssl_certificate_key /opt/nginx/example.com/certs/private/example.key;

    ssl_session_timeout  5m;

    ssl_protocols  SSLv2 SSLv3 TLSv1;
    ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
    ssl_prefer_server_ciphers   on;

    location / {
        root   /opt/nginx/example.com/public_html/www;
        index  index.html index.htm index.php;
    }

    access_log  /opt/nginx/example.com/logs/www/access.log main;

    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /opt/nginx/example.com/public_html/www$fastcgi_script_name;
        include        fastcgi_params;
}

this is basic configuration and please make it as per your needs :)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .