Nginx dynamic matching .dev, subdomain to directory name for developing.
server { | |
listen 127.0.0.1:5002; | |
listen [::1]:5002; | |
server_name .dev; | |
## Set dev's base path in order to appending L1 name | |
set $base_path "/Library/WebServer/Documents"; | |
## Start domain regex match | |
set $domain $host; | |
set $subdomain "\/"; | |
if ($domain ~ "^((.+)\.)?(.*)\.dev$") { | |
## Extract L1 name from accessing domain *.{$domain}.dev | |
set $domain $3; | |
## Extract L2 name from accessing domain {subdomain}.*.dev | |
set $subdomain $2; | |
} | |
## Append subdomain prefix if exists | |
if (-d $base_path/$domain/$subdomain) { | |
set $domain "${domain}/${subdomain}"; | |
## Decide real path depends on $domain_path, | |
## attempting 'dist' for html apps using node | |
## attempting 'public' for backend apps like laravel | |
set $domain_path "${domain}"; | |
if (-d $base_path/$domain_path/dist) { | |
set $domain_path "${domain_path}/dist"; | |
} | |
if (-d $base_path/$domain_path/public) { | |
set $domain_path "${domain_path}/public"; | |
} | |
## Document root from $domain_path | |
root $base_path/$domain_path; | |
location / { | |
index index.html index.php; | |
try_files $uri $uri/ @rewrite; | |
} | |
location @rewrite { | |
if (-f $base_path/$domain_path/index.html) { | |
rewrite ^(.+)$ $uri.html last; | |
} | |
if (-f $base_path/$domain_path/index.php) { | |
rewrite ^(.+)$ $uri.php last; | |
} | |
if (!-f $request_filename){ | |
return 501; | |
} | |
} | |
location ~ \.html$ { | |
try_files $uri /index.html =404; | |
} | |
## Pass the PHP scripts to FastCGI server listening on socket | |
location ~ \.php$ { | |
try_files $uri /index.php =404; | |
fastcgi_split_path_info ^(.+\.php)(.*)$; | |
fastcgi_pass unix:/usr/local/var/run/php-fpm.sock; | |
fastcgi_index index.php; | |
fastcgi_param SCRIPT_FILENAME $realpath_root/$fastcgi_script_name; | |
fastcgi_param DOCUMENT_ROOT $realpath_root; | |
include fastcgi_params; | |
} | |
## Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store(Mac) | |
location ~ /\. { | |
deny all; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment