php - Nginx + PHP-FPM 重定向到静态 PHP 文件
问题描述
首先是关于我的设置的一些细节:
- 我正在从默认 Nginx webroot 提供静态 webapp (HTML + JS)
- 我有一个在 localhost:9000 上运行的 PHP-FPM 服务器
- 目标文件应该是 FPM 的 /api/webroot/index.php (总是,不需要 try_files 等)
- 我需要转发所有/api和/api-debug调用以到达 localhost:9000,并且 /app/webroot/index.php 应该处理所有这些请求。
我有以下工作Nginx 配置:
upstream fastcgi_backend {
server localhost:9000;
keepalive 30;
}
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
location ~ ^/(api|api-debug)/ {
root /app/webroot;
index index.php;
try_files $uri /api/index.php$is_args$args;
location ~ \.php$ {
fastcgi_pass fastcgi_backend;
fastcgi_split_path_info ^(?:\/api\/)(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME /app/webroot/$fastcgi_script_name;
include fastcgi_params;
}
}
}
}
我只是想让它更简单、更高效,因为我现在看到它一团糟。例如,我试图调整
try_files $uri /api/index.php$is_args$args;
至
try_files $uri /api/webroot/index.php$is_args$args;
它失败了......它起作用的唯一原因是/api/index.php包含/api/webroot/index.php,但我认为它效率低下。
我发现调试 nginx 配置很困难,因为它不容易测试。
非常感谢您提前提供的帮助!
解决方案
最简单的解决方案是将 SCRIPT_FILENAME 的值硬连线/app/webroot/index.php
并完全删除您的一个location
块。
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location ~ ^/(api|api-debug)/ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /app/webroot/index.php;
fastcgi_pass fastcgi_backend;
}
或者,为了保持指定带有.php
扩展名的 URI 的灵活性,您可以通过以下方式简化配置:
location / {
root /usr/share/nginx/html;
index index.html index.htm;
rewrite ^/(api|api-debug)/ /index.php last;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /app/webroot$uri;
fastcgi_pass fastcgi_backend;
}
推荐阅读
- c - 数组不兼容的指针类型
- angular - 为什么数组引用分配在打字稿中不起作用?
- python - 以正确的格式打印到终端
- javascript - 百分比宽度即使在跨度内,“溢出-x:滚动”也不起作用
- c# - 将具有嵌套属性的对象打印为逗号分隔的键值对字符串
- java - 如果外部方法失败(使用 javax @TransactionAttribute),我希望不执行我的子方法
- botframework - 如何在 LUIS Bot C# 中附加 AdaptiveCardFromJson?
- java - 在其他注解中使用注解
- javascript - Featherlight 画廊更改上一个和下一个箭头样式
- jquery - 我怎样才能做一个链接做一些jquery然后用一个新的目标去目的地