in Ops

Redirect any subdomain http or https to a single subdomain with NGINX


Today I had a use case where I wanted to redirect any subdomain at any scheme (http or https) to a single https subdomain should redirect to should redirect to

In order to redirect both schemes (http and https) to a single subdomain you have to setup two server blocks. The first one catches all the traffic to any scheme (listen 80; listen 443) at any subdomain (* The second one listens only on port 443 and the specific subdomain

	server {
		listen 80;
		listen 443 ssl;
		server_name *;
		return 301$request_uri;
	server {
		listen 443 default ssl;
		root /var/www/flenny;
		index index.html index.htm;
		ssl on;
		ssl_certificate			path/to/ssl.crt;
		ssl_certificate_key		path/to/ssl.key;
		location / {
			proxy_pass https://x.y.z;

For a specific port you can only have one ssl configuration section (ssl_certificate, ssl_certificate_key). As shown in the example above use the keyword default to flag the appropriate server block.

Important: In order to properly redirect e.g. to you must have a valid ssl certificate for both subdomains.

A full example of a working NGINX configuration you can get here.