How to redirect specific domains or URL’s to HTTPS

in Nginx configuration

Using maps in Nginx it is possible to selectively redirect only certain URL’s or domains to HTTPS.

Go here if you want to  redirect your full site to HTTPS

Redirect specific domains to HTTPS

To redirect only domains that have their own storefront and a SSL certificate to HTTPS, but keep the non-SSL domains on HTTP, create a configuration file /data/web/nginx/http.ssl_maps:

map $host $scheme_for_domain {
  hostnames;
  default "http";
  .example.nl    "https"; 
  .example.com   "https";
  .example.de    "http";
  .example.co.uk "http";
}

Add all domains and the preferred protocol.

Next, add an entry to /data/web/nginx/server.rewrites:

if ($scheme_for_domain != $scheme) { 
    return 301 $scheme_for_domain://$host$request_uri;
}

Now all domains that have SSL specified in the mapping will redirected to HTTPS but leaving the domains without SSL on HTTP.

Redirect specific URL’s to HTTPS

The same trick for domains can be used to redirect specific URL’s to a preferred protocol:

Add another mapping to /data/web/nginx/http.ssl_maps:

map $uri $uri_redirection_scheme {
    default "http";
    ~^/(images|css|javascript)/ "http";
    ~^/sign-up/                 "https";
    ~^/account/                 "https";
    ~^/api/                     "http";
}

You can add any URL to the mapping that should be redirected to a certain protocol.

Next, create an entry in /data/web/nginx/server.rewrites:

if ($uri_redirection_scheme != $scheme) { 
    return 301 $uri_redirection_scheme://$host$request_uri; 
}

And all URL’s listed in the map will be redirected to the specified scheme.

0