Skip to content

Instantly share code, notes, and snippets.

@henno
Last active November 12, 2016 21:38
Show Gist options
  • Save henno/17235e165df16469ca636e0f4cc38108 to your computer and use it in GitHub Desktop.
Save henno/17235e165df16469ca636e0f4cc38108 to your computer and use it in GitHub Desktop.
Nginx configuration for projects as subdirectories (projects.example.com/project1)
#
# cat /etc/nginx/sites-enabled/projects.example.com
#
# Define variable $topdir (top level directory name)
map $request_uri $topdir {
~(?<captured_topdir>^/[a-zA-Z0-9]+)[/] $captured_topdir;
}
server {
server_name _;
listen 80 default;
# Define variable $site
set $site $host;
# Remove potential www from $site
if ($site ~ "^(w{3}\.)?(.*)$") { set $site $2; }
# Define variable $root, based on processed $site variable
set $root /var/www/$site;
# If there is a folder www.$site, set $root to that folder instead
if (-d /var/www/www.$site) { set $root /var/www/www.$site; }
# Write $uri's current value to http response header (for debugging)
add_header X-debug-message "Uri is $uri" always;
# Return 404 when there is no /var/www/$host folder
if (!-d $root) { return 404; }
# Set root to /var/www/$host/public when such folder exists (Laravel etc)
if (-d $root/public) { set $root $root/public; }
# Set access log
access_log /var/log/nginx/$site.access.log;
# Finally, set root to $root, whatever $root is by now
root $root;
# Set directory index file
index index.html index.htm index.php;
# If there requested file/dir does not exist, inject $topdir and the index.php part.
# Stop processing remaining rewrites.
if (!-f $request_filename) {
rewrite ^/(.+)$ $topdir/index.php?url=$1 last;
break;
}
# PHP
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
}
# Do not log static file requests, tell browser to cache them for a year
location ~ ^/(img|images|css|js|ccss|cjs) {
access_log off;
expires 370d;
add_header Cache-Control public;
}
# deny access to hidden
location ~ /\. {
deny all;
}
# Do not log bot and favicon requests
location ~ /(favicon.ico|robots.txt) { log_not_found off; access_log off; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment