-
-
Save ralphotowo/83f8747c046c15142816c4ed754076be to your computer and use it in GitHub Desktop.
Nginx dynamic matching document root by host(accessing domain name) /*USE AT YOUR OWN RISK*/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
server { | |
listen 0.0.0.0:80 default_server; | |
listen [::]:80 default_server; | |
server_name _; | |
server_tokens off; | |
## Document root | |
set $base_path "/usr/share/nginx"; | |
set $domain_path "${host}"; | |
## Strip www prefix from $domain_path | |
if ($domain_path ~* ^www\.(.*)$) { | |
set $domain_path $1; | |
} | |
## Decide real path depends on $domain_path, | |
## attempting 'dist' for html apps using node | |
## attempting 'public' for backend apps like laravel | |
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"; | |
} | |
## No matches found with current domain, resetting path to html | |
if (!-d $base_path/$domain_path) { | |
set $domain_path "html"; | |
} | |
## /var/share/nginx/{ACCESS_DOMAIN_WITHOUT_WWW} or {html} as fallback | |
root $base_path/$domain_path; | |
location / { | |
## Disable gzip compression to be safe against BREACH attack | |
gzip off; | |
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 403; | |
} | |
} | |
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_pass unix:/var/opt/remi/php71/run/php-fpm/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