常用的Nginx配置,包括配置https,gzip,屏蔽敏感目录等。做个笔记。
HTTPS
配置https
上下文:`http
1 | server { |
http请求强制重定向至https
上下文:http
1 | server { |
配置GZip压缩
上下文:http
, server
, location
1 | gzip on; #开启gzip |
pathinfo隐藏index.php
上下文:server
1 | location / { |
Nginx反爬虫
上下文:location
1 | if ($http_user_agent ~* (AhrefsBot|DotBot|MJ12bot|httrack|Findxbot|BLEXBot|WinHttpRequest|Go\s1.1\spackage\shttp|megaindex|BIDUBrowser|FunWebProducts|MSIE\s5|Add\sCatalog|SeznamBot|KomodiaBot|aiHitBot|MojeekBot|PhantomJS|SiteSucker|HTTrack|MegaIndex|BLEXBot|LinkpadBot|Findxbot|SEOkicks|OpenLinkProfiler|PhantomJS|Xenu|007ac9|sistrix|spbot|SiteExplorer|wotbox|ZumBot|ltx71|memoryBot|WBSearchBot|DomainAppender|Python|Aboundex|-crawler|WinHttpRequest|NerdyBot|ZmEu|xovibot)) { |
防SQL注入
上下文:server
1 | if ($query_string ~ "union.*select.*") { |
Nginx禁止通过IP地址访问(只能通过域名访问)
上下文:http
1 | server { |
Nginx 禁止访问敏感目录/文件
上下文: server
Nginx禁止访问敏感目录和文件,按照规范应该返回403错误。但这样存在一个安全隐患,即恶意用户可以通过判断响应代码来区分文件是否存在。返回404错误时,无法判断文件是否存在,是一个比较安全的做法。
禁止访问隐藏文件
1 | location ~ \/\. { return 404; } |
以上配置可以隐藏.env
、.env.example
、.git
、.htaccess
等点号开头的隐藏文件,包括子目录中的隐藏文件。当请求这些隐藏文件时,返回404错误。
禁止访问指定目录
1 | location ~ ^(/runtime|/log|/install) {return 404; } |
以上配置禁止网站访问根目录(不包含子目录)中的runtime
、log
和install
目录。
禁止访问.log日志文件
1 | location ~ \.log$ { return 404; } |
以上配置禁止访问所有.log
结尾的文件,包含网站根目录以及子目录。
Nginx 自定义错误页
上下文: http
, server
, location
1 | error_page 404 /404.html; |