首页| 论坛| 消息
主题:nginx配置文件location使用实例:屏蔽IP/屏蔽蜘蛛/防盗链/重写/重定向等
李唐发表于 2023-04-02 14:10
在上文《nginx.conf location 修饰符解释及示例详解》中,我们对nginx location有了一定的了解,在本文中,我们将继续通过多个实例来了解location指令。
参数解释
location [=|~|~*|^~] /uri/ { … }= 开头表示精确匹配。^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。~ 开头表示区分大小写的正则匹配。~* 开头表示不区分大小写的正则匹配。!~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则。/ 通用匹配,任何请求都会匹配到。location使用实例
1、普通重写
location / { if (!-e $request_filename) { rewrite^(.*)$/index.php?s=$1last; break; } }2、301重定向
server_name xxx.com www.xxx.com; if ($host ~* xxx.com) { rewrite ^/(.*)$ http://www.xxx.com/$1 permanent; }把所有不带www的域名301永久重定向到带www的域名。
3、http跳转https
普通
rewrite ^(.*) https://www.xxx.com$1 permanent; 有cdn
if ( $http_from_https != 'on' ){ rewrite ^(.*) https://www.xxx.com$1 permanent;}4、取消目录执行权限
location ~* ^/(uploads|templets|data)/.*.(php|php5)$ {denyall;}5、屏蔽来源域名
location / {valid_referers www.baidu.com www.360.cn;if ($invalid_referer){return 403;}}6、防盗链
location ~* \.(gif|jpg|png|webp)$ { valid_referers none blocked domain.com *.domain.com server_names ~\.google\. ~\.baidu\.; if ($invalid_referer) {return 403;#rewrite ^/ 图片路径/403.jpg; } root /opt/www/image;}7、屏蔽IP地址
allow 1.1.1.2;allow all;deny all;deny 1.1.1.2 location ^~ /xxx/xxx/xx/{allow 172.0.0.1;allow xxx.xxx.0.0/8;#表示允许xxx.xxx.0.1 ~ xxx.xxx.255.254allow xxx.0.0.0/16;#表示允许xxx.0.0.1 ~ xxx.255.255.254allow xxx.xxx.xxx.x; deny all;}前端还有cdn情况
map $http_x_forwarded_for$clientIp {""$remote_addr;~^(?P[0-9\.]+),?.*$$firstAddr;}if ($clientIp ~* "127.0.0.1|127.0.0.2") { return 403; break;}8、屏蔽蜘蛛
if ($http_user_agent ~ "FeedDemon|JikeSpider|MJ12bot|heritrix|EasouSpider|LinkpadBot|Ezooms" ){return 403;}9、禁止非GET|HEAD|POST方式的抓取
if ($request_method !~ ^(GET|HEAD|POST)$) {return 403;}
回帖(0):

全部回帖(0)»
最新回帖
收藏本帖
发新帖