Location规则

语法规则: location [=|~|~*|^~] /url/ {… }

符号 含义
= = 开头表示精确匹配
^~ ^~开头表示uri以某个常规字符串开头,
理解为匹配url路径即可。
~ ~ 开头表示区分大小写的正则匹配
~* ~* 开头表示不区分大小写的正则匹配
!~和!~* !~和!~*分别为区分大小写不匹配及
不区分大小写不匹配的正则
/ 用户所使用的代理(一般为浏览器)

精确匹配

=

普通匹配

无符号
^~

正则匹配

~
~
!-
!-

安装echo模块

  1. wget https://github.com/openresty/echo-nginx-module/archive/v0.61.zip
  2. tar -zxvf v0.61.zip
  3. cd nginx-1.16.1
  4. nginx -V
  5. ./configure --add-module=/usr/local/src/echo-nginx-module-0.61 --prefix=/usr/local/nginx --with-http_ssl_module
  6. make
  7. mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/
  8. cp objs/nginx /usr/local/nginx/sbin/
  9. nginx -V
  10. nginx -s stop #必须重启后生效 reload无效
  11. nginx

实例

yxj.conf

  1. server{
  2. listen 80;
  3. server_name yxj.mxs223.com;
  4. location /jrf/{
  5. echo '/jrf/';
  6. }
  7. location ~ /jrf/cms/{
  8. echo '~ /jrf/cms/';
  9. }
  10. #location ^~ /jrf/cms/{
  11. # echo '^~ /jrf/cms/';
  12. #}
  13. location /jrf/cms/{
  14. echo '/jrf/cms/';
  15. }
  16. location =/jrf/cms/index.html{
  17. echo '= /jrf';
  18. }
  19. }
  1. curl http://yxj.mxs223.com:8080/jrf/index.html
  2. curl http://yxj.mxs223.com:8080/jrf/cms
  3. curl http://yxj.mxs223.com:8080/jrf/cms/
  4. curl http://yxj.mxs223.com:8080/jrf/cms/index.html

正则匹配优先级


1、location 配合先后顺序与配置文件location 先后顺序无关
2、如果都是普通匹配,最长的会被命中
3、普通匹配会被正则所覆盖
3、^~ 普通匹配 不会被正则所覆盖
4、=精准匹配直接命中

location - 图1

用户中心配置

  1. server {
  2. listen 443 ssl;
  3. server_name www.ruiyi126.com ;
  4. ssl_certificate /app/nginx/cert/2379966_www.ruiyi126.com.pem;
  5. ssl_certificate_key /app/nginx/cert/2379966_www.ruiyi126.com.key;
  6. location /{
  7. proxy_set_header Host $host;
  8. proxy_set_header X-Real-IP $remote_addr;
  9. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  10. proxy_pass https://192.168.0.11;
  11. }
  12. location =/{
  13. proxy_set_header Host $host;
  14. proxy_set_header X-Real-IP $remote_addr;
  15. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  16. proxy_pass https://192.168.0.11/index.jhtml;
  17. }
  18. location ~ \.(gif|jpg|png|js|css|ico)$ {
  19. root /app/work/jinrfucenter_mobile/WebRoot;
  20. }
  21. }

实例 fastdfs 图片缩略图:

  1. location ~(.+)_([0-9]+)x([0-9]+)\.(jpg|gif|png) {
  2. set $w $2;
  3. set $h $3;
  4. add_header Access-Control-Allow-Origin *;
  5. add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
  6. add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
  7. image_filter resize $w $h;
  8. image_filter_buffer 10M;
  9. proxy_pass http://10.10.10.66/$1.$4;
  10. }