问题描述
我有一个非常简单的 PHP 站点:
按指定顺序检查文件是否存在,并使用第一个找到的文件进行请求处理;在当前上下文中执行处理
因此 nginx 查找 PHP 文件并在 location/
的上下文中对其进行处理,因此只需将其作为静态文件使用.只有最后一个参数不同,它没有被检查,但 nginx 进行内部重定向(如果它是 uri)或返回错误代码(如果它是 =code
).因此,您需要从 try_files 中删除 =404
以进行内部重定向.并将 try_files
添加到 location ~ \.php
以确保该文件存在.
location ~ \.php$ {try_files $uri =404;fastcgi_split_path_info ^(.+\.php)(/.+)$;fastcgi_pass unix:/path/to/php.sock;fastcgi_index index.php;包括 fastcgi_params;fastcgi_intercept_errors 开启;}地点/{索引 index.php;try_files $uri $uri/$uri.php;}
I have a very simple PHP site:
.
├── about.php
├── index.php
├── project
│ ├── project_one.php
│ └── project_two.php
└── projects.php
And the following nginx config (only relevant parts shown):
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/path/to/php.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_intercept_errors on;
}
location / {
index index.php;
try_files $uri $uri/ $uri.php =404;
}
Hitting the /
works as expected. Hitting any of the http://my.site.com/{projects | about | project/*}
URLs should use try_files to hit the $uri.php
file, and pass it to PHP. But instead, the browser just downloads the PHP file itself.
I can get it to work by adding individual location directives for the above locations, like so:
location /projects {
try_files $uri $uri/ /$uri.php;
}
location /about {
try_files $uri $uri/ /$uri.php;
}
location /project {
try_files $uri $uri/ $uri.php;
}
But this is clearly not the way to do this.
What am I doing wrong???
Per nginx documentation for try_files
so nginx find PHP file and process it in context of location /
therefor just serve it as static file. Only last parameter is different, it's not checked but nginx make internal redirect (if it's uri) or return error code (if it's =code
). So you need to remove =404
from try_files to have internal redirect. And add try_files
to location ~ \.php
to make sure that file exists.
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/path/to/php.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_intercept_errors on;
}
location / {
index index.php;
try_files $uri $uri/ $uri.php;
}
这篇关于NGINX try_files 不会传递给 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!