Search code examples
nginxdnssubdomaincname

Nginx Domain scheme redirect excluding subdomain


Lets assume I have a domain called example.com along with the following 'n' number of subdomains all of them with 'A' record to same IP address(Assume Server A).

a.example.com,b.example.com,c.example.com ... z.example.com

There is another subdomain 'email.example.com' with CNAME set to 'mailgun.org'.

Now I have Server A with the following nginx configuration wherein I want to forward all HTTP requests to HTTPS.

server {
    listen 80;
    return 301 https://$host$request_uri;
}

And set of code blocks to handle individual sub domain requests to 443.

server {
    listen 443 ssl;
    server_name  a.example.com;
    //SSL Details
    location / {
            root /var/www/a/;
    }

Similarly for rest of the sub domains except email.example.com which points to mailgun.org.

Now, http://email.example.com they will be redirected to http://mailgun.com. (At DNS level)

http://example.com they will be redirected to https://example.com. (At Server level).

http://a.example.com they will be redirected to https://a.example.com. (At server level)

Problem: After visiting to http://example.com, when someone tries to visit http://email.example.com they are being redirected to https://email.example.com by browser. Since I have no control over mailgun.org, I can handle https requests for email.example.com

Is there anyway to set nginx config where in every request to HTTP will be redirected to HTTPS except email.example.com?


Solution

  • Ok, I found the problem.

    I changed my nginx configuration for example.com to not to include subdomains.

    ie., Changed the following line

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    

    as below.,

    add_header Strict-Transport-Security "max-age=31536000;" always;
    

    So that browsers now don't add header to sub domains.