简体   繁体   中英

How to redirect all https domain from www to non www using nginx config file nginx.conf?

I want to redirect all domain from www to non-www using Nginx config file nginx.conf. I have tried using the below configuration but it only work for URL start with HTTP but does not work for HTTPS

I have added below server block

server {
    server_name "~^(?!www\.).*" ;
    return 301 $scheme://$1$request_uri ;
}

Since you didn't specify listening port in the server block you've shown in your question, it will listen on a plain HTTP TCP port 80 by default. You need to specify

listen 443 ssl;

to listen on an HTTPS TCP port 443. However to make the server block workable via the HTTPS protocol, you'd need to specify an SSL certificate/key (at least), and to made a user browser following a redirect returned by nginx, that certificate should be a valid one, issued for the domain name you want to be redirected, or the browser will complain about invalid certificate and won't follow the redirect location.

So if you want to use some kind of universal server block for redirecting every HTTPS request from www to non-www domain, it will be impossible unless you have a certificate that include every domain name you want do redirect (which seems to be impossible to have for a custom non-predefined list of domain names).


Update

Although this isn't a thing I'd do for myself in a production environment, actually there is a way to achieve workable solution using the lua-resty-auto-ssl (see the documentation examples), OpenResty / lua-nginx-module and the following sever block (remember that server names specified by domain prefix have the lowest priority comparing to exact matched server names, eg www.example.com , or server names specified by domain suffix, eg *.example.com ):

init_by_lua_block {
    auto_ssl = (require "resty.auto-ssl").new()
    auto_ssl:set("allow_domain", function(domain)
        return true
    end)
    auto_ssl:init()
}

map $host $basename {
    ~^www\.(.+)  $1;
    default      $host;
}

server {
    listen 443 ssl;
    server_name www.*;

    ssl_certificate_by_lua_block {
        auto_ssl:ssl_certificate()
    }

    ssl_certificate /path/to/dummy.crt;
    ssl_certificate_key /path/to/dummy.key;

    return 301 https://$basename$request_uri;
}

In order for this to work you'd also need the corresponding plain HTTP block to allow ACME challenge(s) to be successfully completed:

server {
    listen 80;
    server_name www.*;

    location / {
        return 301 https://$basename$request_uri;
    }

    location /.well-known/acme-challenge/ {
        content_by_lua_block {
            auto_ssl:challenge_server()
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM