Skip to content

Instantly share code, notes, and snippets.

@Mikulas
Created May 22, 2012 17:57
Show Gist options
  • Save Mikulas/2770600 to your computer and use it in GitHub Desktop.
Save Mikulas/2770600 to your computer and use it in GitHub Desktop.
Nginx dynamic domain with redirect to root
server {
server_name ~^(:?(?<second>.+)\.)?(?<domain>[^.]+\.[^.]+)$;
set $test "";
if ($second !~ "^$") {
set $test "${test}S";
}
if (-d /srv/virtual_hosts/$second.$domain) {
set $test "${test}E";
}
if (-d /srv/virtual_hosts/$domain) {
set $test "${test}D";
}
if ($test ~ "^SE") { # second set and exists
set $sn $second.$domain;
}
if ($test ~ "^SD") { # second set but folder does not exist, redirect to root
rewrite ^(.*)$ http://$domain$1;
return 303;
}
if ($test ~ "^D$") { # second not set, domain folder exists
set $sn $domain;
}
root /srv/virtual_hosts/$sn/www;
try_files $uri $uri/ /index.php;
index index.php index.html;
## Images and static content is treated different
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
access_log off;
expires 30d;
log_not_found off;
}
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ index.php last;
break;
}
}
# pass the PHP scripts to FastCGI (PHP-FPM) server listening on 127.0.0.1:9000
location ~ \.php$ {
include fastcgi_params;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
fastcgi_param SERVER_NAME $sn;
fastcgi_pass 127.0.0.1:9000;
}
}
@Mikulas
Copy link
Author

Mikulas commented Jun 16, 2012

Request Invoked Target
domain.tld /domain.tld/www
sub.domain.tld loads /sub.domain.tld/www if exists, otherwise redirects to domain.tld and invokes /domain.tld/www

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