在上文《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=$1 last;
- 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)$ {
- deny all;
- }
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 ^/ http://www.domain.com/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.254
- allow xxx.0.0.0/16;#表示允许xxx.0.0.1 ~ xxx.255.255.254
- allow xxx.xxx.xxx.x;
- deny all;
- }
前端还有cdn情况
- map $http_x_forwarded_for $clientIp {
- "" $remote_addr;
- ~^(?P<firstAddr>[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;
- }
语法总结
if语句
- #判断访问域名:
- if ($host ~* test.com)
- #判断user_agent:
- if ($http_user_agent ~* "baiduspider" )
- #判断访问来源域名:
- valid_referers www.baidu.com;if ($invalid_referer){return 403;}
- #判断METHOD:
- if ($request_method !~ ^(GET|HEAD|POST)$)
- #判断url中?后参数:
- if ($request_uri ~* ^/list.php\?([^_]+)(_[0-9]+)$)
- #判断url路径地址:
- if ($uri ~* ^/list.php\?([^_]+)(_[0-9]+)$)
- #判断ip:
- if ($remote_addr ~* "127.0.0.1|127.0.0.2")
处理方式
- #禁止访问:
- return 403; deny all;
- #重定向到:
- rewrite ^/(.*)$ http://www.test.com/$1 permanent;
- #重写到:
- rewrite ^(.*)$ /index.php?s=$1 last;
全局变量
- $args
- $content_length
- $content_type
- $document_root
- $document_uri
- $host
- $http_user_agent
- $http_cookie
- $limit_rate
- $request_body_file
- $request_method
- $remote_addr
- $remote_port
- $remote_user
- $request_filename
- $request_uri
- $query
总结
本文通过多个实例介绍了nginx中的location
指令的用法,你还可以阅读此文《nginx.conf location 修饰符解释及示例详解》了解更多有关nginx location的知识。