【nginx泛解析】Nginx泛解析到子目录后自动判断有无public目录详解

时间:2021-08-13  来源:apache  阅读:

我们大家在配置本地 PHP 开发环境时,除非是在 Windows 下,否则我都是偏向于 Nginx + PHP-FPM, 即使 Mac 下已经有了自带的 Apache+PHP 环境,依然如此。一方面是因为 Mac 自带的 PHP 版本不够新(5.6.x),另一方面,Nginx + PHP-FPM 更接近于我的生产服务器环境,而且也方便用 Homebrew 来管理版本和扩展。

在 Mac 下开发 Laravel, 官方提供了 valet, 可以方便地把子目录映射为虚拟主机,但我在使用的时候,遇到一些问题:

真实错误信息难以追踪,总是报 valet 的 index.php 或者 laravel 的 index.php 错误; Symfony 框架里的 config.php/app_debug.php 等无法直接访问。

于是我只保留了 dnsmasq 来管理特定后缀的域名(实现自动解析),然后放弃了 valet,自己做了一个泛解析绑定到本地子目录的配置。

具体配置如下(域名是 *.app):

server {
 listen 80;
 server_name ~^(?.+).app$;
 set $root /Users/kairee/Sites/$subdomain;
  
 if ( -d "/Users/kairee/Sites/$subdomain/public") {
  set $root /Users/kairee/Sites/$subdomain/public;
 }
 root $root;
 charset utf-8;
 client_max_body_size 128M;
 index index.php;
  
 location / {
  try_files $uri $uri/ /index.php$is_args$args;
 }
  
 access_log off;
  
 location ~ \.php\?? {
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  fastcgi_pass unix:/tmp/php.sock;
  fastcgi_index index.php;
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 }
  
 location ~ /\.ht {
  deny all;
 }
}

采用这个配置以后:

如果存在 ~/Sites/domain/public, 则 domain.app 域名的根目录会指向 ~/Sites/domain/public; 如果存在 ~/Sites/domain 但是不存在 ~/Sites/domain/public, 则 domain.app 域名的根目录会指向 ~/Sites/domain; 网站根目录下真实存在的 php 文件可以直接访问,只有不存在的文件才会通过入口文件(index.php)处理; 如果需要支持其它框架,可以在配置文件中加一条 if 语句实现,比如要支持 symfony 的话,复制一下 if 判断块,把 public 改成 web 即可。

我虽然只是用于 mac/linux, 但实际上 Windows 下当然也是可以的,如果你在 Windows 下也使用 Nginx 的话。

【nginx泛解析】Nginx泛解析到子目录后自动判断有无public目录详解

http://m.bbyears.com/jiaocheng/135732.html

推荐访问:nginx配置 nginx负载均衡 nginx怎么读
相关阅读 猜你喜欢
本类排行 本类最新