简体   繁体   中英

nginx rewrite for subsubdomains to subdomains

We have an application where we use subdomains for each of our customer's installations. so we have customer1.ourapp.com, customer2.ourapp.com, customer3.ourapp.com and so on.

Because of security we want to redirect all http to https, since we have a wildcard SSL certificate. Also, some customers are not that tech savvy and add www to their domain name, so then you get things like: http://www.customer1.ourapp.com or https://www.customer1.ourapp.com . In those cases the SSL certificate isn't valid because of the subsubdomain.

I'm trying to write the vhost config for nginx to make the correct redirect in these two cases. I got the http to https redirect to work with:

server {
    listen      80;
    server_name *.ourapp.com;

     #Rewrite all nonssl requests to ssl.
     return 301 https://$host$request_uri$is_args$args;
}

correct url's use:

server {
    listen      443;
    server_name *.ourapp.com;

     #Rest of config
}

Made an attempt for the subsub domains, but it's not matching:

server {
        server_name "~^(.*)\.(.*)\.ourapp\.com$";
        return 301 https://$2.ourapp.com$request_uri;
}

Any idea how to get this working?

Wildcarded server takes precedence over regexp'ed one and matches 'www...' too. You can use one definition for both cases:

server_name ~ ^(?:.*\.)?(.*)\.ourapp\.com$;
return 301 https://$1.ourapp.com$request_uri;

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