【发布时间】:2019-08-08 06:46:31
【问题描述】:
我正在尝试在 mydomain/backend 下提供我的 PHP 项目,因为我想为 Node / Vue 项目保留我的基本 URL。我将问题归结为由于 try+files 和 ~.php 块之间的交互,我无法让 PHP 应用程序在 /backend 下运行。
关于如何实现这一点的任何建议?如果我只是删除 /backend 并通过我的根位置访问应用程序,一切都会正常工作/
server {
listen 80;
listen [::]:80;
root /var/www/backend/public;
index index.php index.html index.htm;
server_name your-domain.com;
#location ^~ /backend/ {
location /backend {
# This is the folder that index.php is in
try_files $uri $uri/ /index.php?_url=$uri&$args;
}
location ~ [^/]\.php(/|$) {
fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
fastcgi_index /index.php;
include fastcgi_params;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
奇怪的是,PHP项目的相对路由其实是在导航到/backend的时候触发的,但是项目的实际内容却不见了。我希望项目的根目录是 /domain/backend,项目中的所有 URL 都以 /backend 为前缀
我也尝试在 ~.php 块中添加 /backend,但无济于事。
更新:
感谢您的回复。我已经接近解决方案了,但还没有完全解决。
按照您的提示和以下链接,我学到了以下内容: How to properly configure alias directive in nginx?
- 如果在某个位置使用别名,则不应使用 try_files 由于长期存在的错误而被阻止
- fastcgi_param SCRIPT_FILENAME $request_filename;应该使用 而不是 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;如果你使用别名
- 如果你做第2点,你应该使用索引index.php;代替 fastcgi_index /index.php;
但是使用 updated.conf 文件,我的 PHP 应用程序仍会重新路由到原始 URL。
重写行有什么问题?为什么 /backend 仍然像项目在 / 中一样路由回?它正在由 PHP 应用程序获取,因为 Node 应用程序对所有其他随机不存在的子 URI 进行 404。
做线条
fastcgi_split_path_info ^(.+?.php)(/.*)$;
和
fastcgi_param PATH_INFO $fastcgi_path_info;
由于将它们嵌套在别名块中而产生任何副作用?
如何正确地 try_files $uri $uri/ /index.php?_url=$uri&$args;在别名块内工作?
server {
listen 80;
listen [::]:80;
server_name your-domain.com;
location ^~ /backend {
alias /var/www/back/public;
index index.php index.html index.htm;
if (!-e $request_filename) { rewrite ^ /backend/index.php?_url=$uri&$args last; }
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
index index.php;
include fastcgi_params;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $request_filename;
}
}
location / {
# node/Vue project
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
【问题讨论】:
-
感谢您的回复。我已经接近解决方案,但还没有完全解决。我已根据您的建议更新了我的 .conf 文件,但仍然没有达到预期的效果。
-
fastcgi_split_path_info指令在您的情况下没有任何作用,并且可以与fastcgi_param PATH_INFO语句一起删除。当您说“重新路由”时,如果您的意思是 PHP 应用程序正在重定向到一个不以/backend开头的 URI,那么这是 PHP 应用程序而不是 Nginx 的问题。