dpl22899 2015-12-21 07:09
浏览 92
已采纳

如何通过同一PHP文件提供来自子路径的所有请求?

I'm pulling out my hair trying to get the following setup to work on my machine and on Heroku:

  • main pages are PHP files residing in the document root
  • there's an API under root/api. All requests to /api/* should be forwarded to its gateway file (api/index.php).

Locally I got this to work with a different conf file (below), but on Heroku nothing is working correctly. The best I could figure out was this:

location / {
    try_files $uri $uri/ /index.php?$query_string;
    index index.php;
}
location ~ ^/api/(.+) {
    try_files /api/index.php /api/index.php;
}
location ~ \.php(/|$) {
    try_files @heroku-fcgi @heroku-fcgi;
}

If I try to use rewrite, it complains of an infinite loop. If I try to set the gateway script as index and use try_files with their FCGI location, I get 404 - as there's nothing under the /api folder besides that script.
Using try_files and pointing the script directly makes Heroku send the .php file directly for download instead of interpreting it. How can I make it be interpreted, and still override all other /api/* requests?


Conf file working on my local machine:

server {
    listen        80;
    server_name   devshop.dev;

    index index.php;
    root  /home/myself/dev/developer-shop/www/;

    location ~ ^/api(/|$) {
        try_files $uri $uri/ /api/index.php;
        include       /etc/nginx/fastcgi_params;
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
    }

    location ~ \.php(/|$) {
        include       /etc/nginx/fastcgi_params;
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
    }
}
  • 写回答

1条回答 默认 最新

  • dsk95913 2015-12-21 10:05
    关注

    On your local machine PHP scripts are handled within their respective location block. On your target machine the /api/ location performs an internal rewrite which is then expected to be handled by the php block.

    Regex location blocks are ordered so that /api/index.php keeps hitting the /api/ location block - hence the redirection loop.

    Either reverse the order of the regex location blocks or more simply, use a prefix location block with a rewrite:

    location /api {
        rewrite ^ /api/index.php;
    }
    

    See this document for details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)