Nginx [SOLVED]: Redirecting www to non-www

Nginx [SOLVED]: Redirecting www to non-www

Home Forums Nginx Nginx [SOLVED]: Redirecting www to non-www

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #36701

    Anonymous

    QuestionQuestion

    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?

    #36702

    Anonymous

    Accepted AnswerAnswer

    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;
        ...
    }
    

    Source: https://stackoverflow.com/questions/47961644/redirecting-www-to-non-www
    Author: Tarun Lalwani
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.