Nginx如何使用一个域名配置多个目录

server {
    listen       *:80;
    server_name  admin.hiphop.top;

    location / {
        root   "D:\Office\PHPStudy\PHPTutorial\WWW\MyWork\VhiphopAdmin\dist";
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    location /api {
        root   "D:\Office\PHPStudy\PHPTutorial\WWW\MyWork\VhiphopAdminApi\public";
        index  index.php;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php(.*)$  {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

配置代码如上
访问 admin.hiphop.top
可以匹配到 "D:OfficePHPStudyPHPTutorialWWWMyWorkVhiphopAdmindist"

访问 admin.hiphop.top/api
不能匹配到 "D:OfficePHPStudyPHPTutorialWWWMyWorkVhiphopAdminApipublic"

dist目录是我的前端静态文件, public目录是php api接口的入口目录
请问如何配置才能做到 访问 admin.hiphop.top/* 时匹配dist目录
并且访问 admin.hiphop.top/api 优先匹配php的public目录

配置2个域名是没问题的 因为浏览器有跨域问题, 所以现在想只用一个域名

阅读 4.4k
2 个回答

访问http://admin.hiphop.top/api/test.html这个url情况下,$uri/api/test.html
使用 root的情况下,判断的是D:\Office\PHPStudy\PHPTutorial\WWW\MyWork\VhiphopAdminApi\public\api目录下有没有这个文件

要想访问到正确的文件,有两种方法:

  1. root 改为 alias

    alias "D:\Office\PHPStudy\PHPTutorial\WWW\MyWork\VhiphopAdminApi\public\";
  2. public目录下增加一个api目录, 然后配置不变

附: alias和root的区别

aliasroot的区别在于怎么理解location后面的uri

  • rootroot路径 + location路径
  • alias 是用alias路径替换location路径

问题已经解决了 在最后一个.php匹配规则里面加上root就可以了

    location ~ \.php(.*)$  {
        root   "D:\Office\PHPStudy\PHPTutorial\WWW\MyWork\VhiphopAdminApi\public";
        index  index.php;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题