Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active December 5, 2017 12:35
Show Gist options
  • Save magnetikonline/4303186 to your computer and use it in GitHub Desktop.
Save magnetikonline/4303186 to your computer and use it in GitHub Desktop.
Nginx snippets collection.
# deny access to any Git repository related files/directories
# useful if using "git push" is part of your web application deployments
location ~ "\.git(?:$|/|attributes$|ignore$|modules$)" {
return 404;
}
location ~ "\.htaccess$" {
return 404;
}
# unless a direct file request, ensure URL ends with forward slash
if ($uri !~ "\.[a-z0-9]{2,4}$") {
rewrite "[^/]$" $scheme://$host$uri/ permanent;
}
# remove multiple sequences of forward slashes
# rewrite URI has duplicate slashes already removed by Nginx (merge_slashes on), just need to rewrite back to current location
# note: the use of "^[^?]*?" avoids matches in querystring portion which would cause an infinite redirect loop
if ($request_uri ~ "^[^?]*?//") {
rewrite "^" $scheme://$host$uri permanent;
}
# rewrite CSS/JavaScript release cache busted requests
rewrite "^/[a-f0-9]{16}/(css|js)/(.+)$" /$1/$2? break;
# rewrite CSS/JavaScript release cache busted requests and set far forward expiry time
location ~ "^/[a-f0-9]{16}/(?<resource_type>css|js)/(?<resource_path>.+)" {
expires 30d;
rewrite "^" /$resource_type/$resource_path? break;
}
server {
listen 80;
server_name www.domain.com;
return 301 $scheme://domain.com$request_uri;
}
server {
listen 80;
server_name domain.com;
# nginx config for virtualhost goes here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment