【发布时间】:2016-05-30 00:42:36
【问题描述】:
我想用 NGINX 提供静态 HTML 文件,但如果文件丢失,它应该加载一个 PHP 文件,而 PHP 应该处理内容。
我一直在测试try_files 的几种组合,但我无法理解它。我有一个看起来像这样的虚拟 PHP 应用程序:
./
../
dynamic.php
index.php
static/
static/static.html
然后我在索引上有一个小的 PHP 代码,如下所示:
<?php
$path = $_SERVER['REQUEST_URI'];
$pattern = '/^\/(.*)\.html$/';
$matches = [];
$results = preg_match($pattern, $path, $matches);
if (count($matches) > 0) {
if ($matches[1] == "dynamic") {
require 'dynamic.php';
} else {
echo "Not found!";
}
} else {
echo "Index page!";
}
浏览到每个页面的结果应该是:
http://foo.bar/ - Loads index.php
http://foo.bar/static.html - Loads static/static.html
http://foo.bar/dynamic.html - Loads index.php & PHP requires dynamic.php
http://foo.bar/baz.html - Loads index.php with "not found" message
这是我在 NGINX 配置文件中得到的:
server {
listen 80;
server_name .foo.bar *.foo.bar;
access_log /var/log/nginx/foo.access.log;
error_log /var/log/nginx/foo.error.log;
root /var/www/foo;
index index.php;
location / {
# Trying with 'try_files' here. No success.
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm-foo.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
我一直在反复尝试,显然这行完全失败了:
try_files $uri $uri/static /index.php;
我错过了一些东西。帮忙?
【问题讨论】:
-
在您的情况下是否可以进行一些 URL 重写但一直使用 PHP 处理显示的页面?