Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx Redirect HTTP to HTTPS and WWW to Non-WWW

I'm having issues with this config:

#=========================#
# domain settings #
#=========================#

# Catch http://domain, and http://www.domain
server {
        listen 80;
        server_name www.domain domain;

        # Redirect to https://domain
        return 301 https://domain$request_uri;
}

# Catch https://www.domain
server {
        listen 443;
        server_name www.domain;

        # Redirect to https://domain
        return 301 https://domain$request_uri;
}

# Catch https://domain
server {
        listen 443;
        server_name domain;

        root /usr/share/nginx/domain;
        index index.html index.htm;

        ssl on;
        ssl_certificate /etc/nginx/ssl/server.crt;
        ssl_certificate_key /etc/nginx/ssl/server.key;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
        ssl_prefer_server_ciphers on;

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

Something is wrong with the 3rd server directive. I get a SSL connection error. But when I comment our that section everything works fine. But I want www to redirect to non-www over https also

Can anyone spot the problem?

like image 682
Carson Evans Avatar asked Oct 09 '15 22:10

Carson Evans


People also ask

How do you configure HTTP to https redirect in nginx?

Redirect HTTP to HTTPS version for Specified domain in NginxServer_name domain-name.com www.domain-name.com – it specifies the domain names. So, replace it with your website domain name that you want to redirect. Return 301 https://domain-name.com$request_uri – it moves the traffic to the HTTPS version of the site.


1 Answers

The Nginx configuration snippet below will enable you effectively redirect all http traffic to https while stripping any eventual www prefix.

As such, your site will strictly be available over https and without the www prefix.

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

    server_name www.example.com example.com;

    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    if ($host = www.example.com) {
        return 301 https://example.com$request_uri;
    }

    server_name www.example.com example.com;

    # SSL configuration
    # Other configurations
}

With reference to if is evil, do note that it is safe to use the if directive as it is not used in a location context.

like image 66
nyedidikeke Avatar answered Nov 13 '22 22:11

nyedidikeke