zoukankan      html  css  js  c++  java
  • [PHP] 深度解析Nginx下的PHP框架路由实现


    所有的框架处理业务请求时,都会处理URL的路径部分,分配到指定的代码中去处理。
    实现这一功能的关键就是获取$_SERVER全局变量中对于URL部分的数据

    当请求的路径为
    http://test.com/article?id=1
    http://test.com/article/update?id=1


    支持以上url模式,不需要配置传递PATH_INFO变量,也不需要配置伪静态去除index.php
    最简单的nginx配置如下:

    server {
            listen 80; 
            server_name  test.com;
            access_log  /var/log/nginx/test.com.access.log  main;
            root   /home/test;
            index  index.html index.htm index.php;
            location / { 
                    try_files $uri $uri/ /index.php?q=$uri&$args;
            }   
            location ~ .php {
                    fastcgi_pass   127.0.0.1:9000;
                    fastcgi_index  index.php;
                    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                    include        fastcgi_params;
            }   
    }

    此配置有几个重点要关注:
    1.try_files必须配置在location块中,这个可以用于除去index.php,如果不配置,则必须在路径中加上/index.php/
    2.location ~ .php
    a. 这里是否以$结尾,有时会被困扰,重点看清是否存在try_files,如果不存在try_files指令,那么就一定不要以$结尾,这样在路径中使用带/index.php/的模式还是可以访问的
    b. 如果存在try_files指令,并且location ~ .php$ 这里是以$结尾,那么/index.php/在php的location中就匹配不到,但是try_files又把参数重写到index.php?q=中了,因此这样也是可以访问到

    此时$_SERVER变量中,经常被各大框架或者自写程序用作路由处理使用的变量值如下:
    $_SERVER["PHP_SELF"]=>"/index.php",没有URL中的参数
    $_SERVER["PATH_INFO"]=>,根本不存在,因为Nginx没有传递这个变量

    $_SERVER["REQUEST_URI"]=>"/article/update?id=1",这个是实现路由的关键,参数都存在


    PHP中比较兼容的处理是:
    $uri=$_SERVER['REQUEST_URI'];
    $uri=str_replace("/index.php","",$uri);
    if(strpos($uri,"?")!==false){
    $uri=substr($uri,0,strpos($uri,'?'));
    }
    $uri=trim($uri,'/');

    var_dump($uri);//获取到 article/update

  • 相关阅读:
    PAT (Advanced Level) 1010. Radix (25)
    PAT (Advanced Level) 1009. Product of Polynomials (25)
    PAT (Advanced Level) 1008. Elevator (20)
    PAT (Advanced Level) 1007. Maximum Subsequence Sum (25)
    PAT (Advanced Level) 1006. Sign In and Sign Out (25)
    PAT (Advanced Level) 1005. Spell It Right (20)
    PAT (Advanced Level) 1004. Counting Leaves (30)
    PAT (Advanced Level) 1001. A+B Format (20)
    PAT (Advanced Level) 1002. A+B for Polynomials (25)
    PAT (Advanced Level) 1003. Emergency (25)
  • 原文地址:https://www.cnblogs.com/taoshihan/p/11441214.html
Copyright © 2011-2022 走看看