Nginx PHP-FastCGI:在baseurl / backend /而不是baseurl /

时间:2019-08-06 23:38:00

标签: php nginx

我想在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;
    }
}

奇怪的是,导航到/ backend时实际上触发了PHP项目的相对路由,但是缺少了项目的实际内容。我希望项目的服务就像项目的根是/ domain / backend,项目中的所有URL都带有/ backend前缀

我也尝试在〜.php块中添加/ backend,但无济于事。

更新:

感谢您的回复。我已经接近解决方案了,但是还没有解决。

按照您的提示以及以下链接,我学到了以下内容: How to properly configure alias directive in nginx?

    如果在位置内使用别名,则不应使用
  1. try_files 由于长期存在的错误而被阻止
  2. fastcgi_param SCRIPT_FILENAME $ request_filename;应该使用 而不是fastcgi_param SCRIPT_FILENAME $ document_root $ fastcgi_script_name;如果您使用别名
  3. 如果执行第2点,则应使用index 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;
    }
}

1 个答案:

答案 0 :(得分:0)

尝试先设置根目录位置,然后再设置/ backend位置,并为您的PHP项目添加别名。

类似这样的东西:

root /var/www;

location / {
   # Directives for your Vue project
}

location /backend {
    alias /var/www/backend/public;
    try_files $uri $uri/ /index.php?_url=$uri&$args;
}