Nginx如何实现pathinfo模式的方法详解

2019-10-17 18:13:55刘景俊

通过以上配置就能达到补全 index.php 入口文件的效果了。

区分符号 ?前后的内容

在通用的 URL 中,符号“?”是具有特殊作用的,它是用来将查询字符串和前面的文件隔开。在 pathinfo 模式的 URL 中,符号“?”没有了,也就是说,服务器无法区分 URI 中哪些是文件,哪些是查询字符串了。所以,我们的目的是将 pathinfo 模式中本来应该由符号“?”区分的内容给手动区分开来。

还好,Nginx 中有个指令可以实现我们的目的,fastcgi_split_path_info。它可以将正则表达式定义的两个串分别赋值给变量 $fastcgi_script_name 和变量 $fastcgi_path_info,以供后文使用。更多关于 fastcgi_split_path_info 的信息,请查阅这里

相关配置类似下面的代码:

location ~ ^(.+.php)(.*)$ {
 root /var/www/html/$vhost_path;
 fastcgi_pass phpfpm:9000;
 fastcgi_split_path_info ^(.+.php)(.*)$;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 fastcgi_param PATH_INFO $fastcgi_path_info;

 include fastcgi_params;
}

一个简单的例子

通过上面两部份的配置,现在的 Nginx 服务器已经支持 pathinfo 模式的 URL 了,以下是一个简单的 server 配置,仅供参考:

server {
 listen 80;
 server_name tp5.loc;

 set $vhost_path tp5/public;

 location / {
 root /usr/share/nginx/html/$vhost_path;
 index index.php index.html index.htm;

 if (!-e $request_filename) {
  rewrite ^/(.*)$ /index.php/$1 last;
 }
 }

 location ~ ^(.+.php)(.*)$ {
 root /var/www/html/$vhost_path;
 fastcgi_pass phpfpm:9000;
 fastcgi_split_path_info ^(.+.php)(.*)$;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 fastcgi_param PATH_INFO $fastcgi_path_info;

 include fastcgi_params;
 }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。