synchroni_city
synchroni_city

Reputation: 159

Redirecting www to non-www

I'm trying to redirect all traffic from an HTTP site to an HTTPS site as well as all www traffic to the non-www site. My setup includes an nginx.conf file for the HTTP site which I've added a 301 redirect rule to:

server {
    listen       80;
    listen       [::]:80;
    server_name
        sub.domain.com
        www.sub.domain.com
       ;

    return 301 https://sub.domain.com$request_uri;
    ...
}

I also have an https nginx.ssl.conf file which looks something like:

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name  sub.domain.com www.sub.domain.com;

    ssl on;
    ...
}

With this setup, I'm able to redirect all HTTP traffic to HTTPS but if I try to add a redirect in my nginx.ssl.conf file I receive a "too many redirects" error.

Any suggestions on how I can redirect everything to my HTTPs, non-www site?

Upvotes: 0

Views: 198

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146490

You need to split your https block into two domains

server {
    listen       80;
    listen       [::]:80;
    server_name
        sub.domain.com
        www.sub.domain.com
       ;

    return 301 https://sub.domain.com$request_uri;
    ...
}


server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name  www.sub.domain.com;
    return 301 https://sub.domain.com$request_uri;
    ssl on;
    ...
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name  sub.domain.com;

    ssl on;
    ...
}

Upvotes: 1

Related Questions