Skip to content

Instantly share code, notes, and snippets.

@image72
Forked from v1shwa/dynamic_subdomains
Created April 9, 2022 20:56
Show Gist options
  • Save image72/0ba79d7faefd36232b9b0e34ba8ab65d to your computer and use it in GitHub Desktop.
Save image72/0ba79d7faefd36232b9b0e34ba8ab65d to your computer and use it in GitHub Desktop.
Dynamically map subdomains to different ports on the server - using Nginx
server {
listen 80;
# maps p8080.example.com -> localhost:8080
server_name ~^p(?<port>[^.]+)\.example\.com$;
location / {
proxy_pass http://localhost:$port;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
  • You need to create an wilcard A record for the domain(or subdomain) first.

    A * points to 1.2.3.4 Automatic

  • Create an nginx config file with above content & restart the web server.

  • Done.

@image72
Copy link
Author

image72 commented Apr 9, 2022

map directory to subdomain

server {
	if ($host ~* ^[^.]+\.[^.]+$|^[^.]+\.co\.in$) {
		set $host_without_www $1;
		rewrite ^(.*)$ http://www.$host$1 permanent;
	}

	if ($host ~* "^(.+)\.([a-z0-9]*)((?<!.co)\.in|\.us|\.org|\.info|\.me|\.net|\.com|\.co|\.co\.in)$"){
		set $subdomain $1;
		set $maindomain $2$3;
		set $htdocs $maindomain/$subdomain;
	}
	
	listen       80;
	server_name  _;

	set $root_path /home/user;

	root   $root_path/www/$htdocs;
	index  index.html index.hml index.php;

	error_log	$root_path/log/error.log warn;
	access_log	$root_path/log/$subdomain.$maindomain.access.log main;

	# Support Clean (aka Search Engine Friendly) URLs
    location / {
		try_files $uri $uri/ /index.php?q=$uri&$args;
    }

	# deny running scripts inside writable directories
    location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ {
        return 403;
        error_page 403 /403_error.html;
    }

	location = /favicon.ico { access_log off; log_not_found off; error_log off;}

	location ~ \.php$ {
		fastcgi_pass   127.0.0.1:9000;
		fastcgi_index  index.php;
		fastcgi_param  SCRIPT_FILENAME  $root_path/www/$htdocs$fastcgi_script_name;
		include        fastcgi_params;
	}

	# caching of files 
    location ~* \.(ico|pdf|flv)$ {
		expires 1y;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|swf|xml|txt)$ {
		expires 30d;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment