Nginx:在特定路径组件的别名内路由到 index.php

Nginx:在特定路径组件的别名内路由到 index.php

我正在尝试让 nginx 路由到特定路径别名内的 index.php。使用子域(并添加具有不同名称的服务器块)会更容易,但我的项目出于几个非主题原因需要这种结构。简而言之,我想要以下内容:

1. www.example.com         --> /home/user/www/public/index.php
2. www.example.com/a/b     --> /home/user/www/public/index.php
3. www.example.com/api     --> /home/user/api/public/index.php
4. www.example.com/api/a/b --> /home/user/api/public/index.php

1 和 2 非常标准:始终提供 index.php 文件(在某个根目录中)并让 php 负责路由。3 模拟子域构造(并且应该指向不同目录中的 index.php)。

我设法让 1-3 号起作用,但 4 号不起作用。每当我访问 www.example.com/api/a/b 时,它都会给出 404。错误日志告诉我 nginx 正在尝试为我提供 /home/user/api/public//a/b/。我觉得我已经非常接近解决方案了,但似乎没有得到正确的结果。我也可以以同样的方式提供静态文件。

以下配置是相关的:

server {
    listen 80;
    server_name example.com www.example.com;
    root /home/user/www/public;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php;
    }
    location ~ \.php$ {
            try_files $uri /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_index   index.php;
            fastcgi_pass    unix:/var/run/php5-fpm.sock;
            include         fastcgi_params;
            fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    } 
    location /api {
        alias /home/user/api/public/;

        location ~ \.php$ {
           try_files $uri /index.php =404;
           fastcgi_split_path_info ^(.+\.php)(/.+)$;
           fastcgi_index   index.php;
           fastcgi_pass    unix:/var/run/php5-fpm.sock;
           include         fastcgi_params;
           fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
         }
    }      
}

提前致谢。

解决方案

server {
    listen 80;
    server_name example.com www.example.com;
    root /home/user/www/public;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php;
    }
    location ~ \.php$ {
            try_files $uri /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_index   index.php;
            fastcgi_pass    unix:/var/run/php5-fpm.sock;
            include         fastcgi_params;
            fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    } 
    location /api/ {
        alias /home/user/api/public/;
        try_files $uri /api/index.php =404;

        location ~ \.php$ {
           try_files $uri /index.php =404;
           fastcgi_split_path_info ^(.+\.php)(/.+)$;
           fastcgi_index   index.php;
           fastcgi_pass    unix:/var/run/php5-fpm.sock;
           include         fastcgi_params;
           fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
         }
    }      
}

答案1

您已经非常接近了。但您需要匹配 的尾随/字符location及其对应的alias

您还需要在该块中添加try_files来引用正确的index.php,这可能是/api/index.php

    location /api/ {
        alias /home/user/api/public/;
        try_files $uri /api/index.php;

相关内容