Home > Software design >  Nginx Redirect Chaining
Nginx Redirect Chaining

Time:07-20

This is What I have

http://example.com ---> https://www.example.com ---> https://example.com

This is what I am trying to Achieve

http://example.com ---> https://example.com

My current nginx config has the below mentioned line

if ($real_scheme = 'http') { return 301 https://$host$request_uri; }

Where real_scheme is a variable derived from a Map block

I am trying to Achieve the same using a Map, can anyone lemme know the mistake I am making, Below is the updated Config

map $host $nonwwwhost {
~*^www\.(.*)   $1;   
default     $host;
}

if ($real_scheme = 'http') { return 301 https://$nonwwwhost$request_uri; }

CodePudding user response:

I would say that using map for https redirects is discouraged, because the standard practice is allocating server blocks with redirects set up inside them.

There are a total of 3 server blocks required to cover redirecting to your desired canonical domain name and port.

Redirections flow can be different, but I suggest following with HSTS redirect requirements.

In a case where your canonical domain is example.com and not www.example.com, these would be your server blocks:

server {
    listen 80; 
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}
server {
    listen 443 ssl http2;
    more_set_headers "Strict-Transport-Security: max-age=31536000; includeSubDomains; preload";
    ssl_certificate ...;
    ssl_certificate_key ...;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}
server {
    listen 80; 
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}
server {
    listen 443 ssl http2;
    more_set_headers "Strict-Transport-Security: max-age=31536000; includeSubDomains; preload";
    ssl_certificate ...;
    ssl_certificate_key ...;
    server_name example.com;
    ... main website directives go here
}

This kind of setup ensures, that should a visitor first access http://www.example.com, he is first redirected to https://www.example.com and then https://example.com, ensuring his browser obtains HSTS policy accordingly.

CodePudding user response:

Finally figured out a way to Achieve this using regex expression

map $host $nonwwwhost {
~*^www\.(?<domain3>\S )*  $domain3;
default     $host;
}
  • Related