我正在尝试使用php代码向站点的/ blog子目录提供请求,该代码位于文档根目录之外的文件夹中。这是我的主机配置:
server {
server_name local.test.ru;
root /home/alex/www/test2;
location /blog {
alias /home/alex/www/test1;
try_files $uri $uri/ /index.php$is_args$args;
location ~ \.php$ {
fastcgi_split_path_info ^(/blog)(/.*)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
}
}
}
我得到像
这样的请求wget -O - http://local.test.ru/blog/nonExisting
只是来自/ home / alex / www / test2 /文件夹的index.php文件的代码。
然而,这个配置:
server {
server_name local.test.ru;
root /home/alex/www/test2;
location /blog {
alias /home/alex/www/test1;
try_files $uri $uri/ /blog$is_args$args;
index index.php;
location ~ \.php$ {
fastcgi_split_path_info ^(/blog)(/.*)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
}
}
}
从/ home / alex / www / test2 /给我index.html文件。 请给我一个线索 - 为什么?我怎样才能强制NGINX处理/home/alex/www/test1/index.php呢?
答案 0 :(得分:24)
我们无法通过在位置块中指定root来使其工作。我们的解决方案是使用别名。请注意,必须在try_files指令中重复位置的路径两次,然后在.php配置块中重复:
server {
server_name localhost;
root /app/frontend/www;
location /backend/ {
alias /app/backend/www/;
# serve static files direct + allow friendly urls
# Note: The seemingly weird syntax is due to a long-standing bug in nginx: https://trac.nginx.org/nginx/ticket/97
try_files $uri $uri/ /backend//backend/index.php?$args;
location ~ /backend/.+\.php$ {
include fastcgi_params;
fastcgi_buffers 256 4k;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_param HTTPS $proxied_https;
fastcgi_pass phpfiles;
}
} # / location
}
中debian-php-nginx stack的the docker-stack project来源
答案 1 :(得分:22)
这是a long standing bug in nginx。但是你可以再次使用root
指令来解决这个问题。有点黑客,但至少它有效。
server {
index index.php;
root /home/alex/www/test2;
server_name local.test.ru;
location /blog {
root /home/alex/www/test1;
try_files $uri $uri/ /blog$is_args$args;
}
}
答案 2 :(得分:4)
还有另一种解决方法可以提供更大的灵活性。它由指向127.0.0.1的proxy_pass
指令和另一个server
块组成。
在你的情况下它应该是这样的:
upstream blog.fake {
server 127.0.0.1;
}
server {
server_name local.test.ru;
root /home/alex/www/test2;
index index.html;
location /blog {
proxy_pass http://blog.fake/;
}
}
server {
server_name blog.fake;
root /home/alex/www/test1;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php(/|$) {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
}
}