[PHP] PHP routing framework implemented in depth analysis Nginx


All frames are processed the service request, the processing will be path portion of the URL assigned to the specified code to handle.
The key to this function is to get $ _SERVER global variable data for part of the URL

When the path request is
http://test.com/article?id=1
http://test.com/article/update?id=1


Support above url mode, no configuration pass variables PATH_INFO, pseudo-static configuration does not need to remove index.php
easiest nginx configuration is as follows:

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;
        }   
}

 

This configuration has to pay attention to several key:
1.try_files location must be configured in the block, this can be used to remove index.php, if not configured, you must add in the path /index.php/
2.location ~ \. PHP
a. here whether the $ end, sometimes troubled, to see whether there is a focus on try_files, if try_files instruction does not exist, then it must not end with $, so use with /index.php/ pattern in the path can still access
b. If try_files directive exists, and location ~ \ .php $ $ here is the end, then /index.php/ in on the location php not match, but try_files again rewrite the parameter to index.php? q = in, so this is also accessible to

At this time, the variable $ _SERVER variable, often used as the major framework or routing process used to write a program from the following values:
$ _SERVER [ "PHP_SELF"] => "/ the index.php", no parameters in the URL
$ _SERVER [ "PATH_INFO"] =>, it does not exist, because this variable is not passed Nginx

$ _SERVER [ "REQUEST_URI"] => "/ article / update? Id = 1", this is the key to routing parameters are present


PHP is the more compatible processing:
$ uri = $ _ SERVER [ 'REQUEST_URI'];
$ uri = str_replace ( "/ index.php", "", $ uri);
IF (strpos ($ uri, "")?! to false ==) {
$ URI = substr ($ URI, 0, the strpos ($ URI, '?'));
}
$ = TRIM URI (URI $, '/');

var_dump ($ uri); // get the article / update

Guess you like

Origin www.cnblogs.com/taoshihan/p/11441214.html