如何将多个路径放入 nginx 中的同一个域?

How can I put multiple paths into the same domain in nginx?

我想将 domain.com/c 连接到 /var/www/a/c 并将 domain.com/b 连接到 /var/www/b。我写了如下的 nginx 站点可用文件:

server {
    listen 443 ...

    index index.php index.html;
    server_name domain.com;
    root /var/www/a;

    location / {
        try_files $uri $uri/ =404;
    }

    location /b {
        root /var/www/b;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.0-fpm.sock;
    }
}

但是我输入 domain.com/b 时看到 404。我尝试使用 alias 而不是 root 但我得到了相同的结果。我该怎么办?

这是因为您的 location ~ \.php$ { ... } 使用了您的全局 root /var/www/a;。在许多其他解决方案中,这只是两个可能的解决方案:

  1. 使用嵌套的 PHP 处理程序:

    server {
        listen 443 ...
    
        index index.php index.html;
        server_name domain.com;
        root /var/www/a;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location ^~ /b/ {
            root /var/www;
            try_files $uri $uri/ /b/index.php?$query_string;
            location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php8.0-fpm.sock;
            }
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.0-fpm.sock;
        }
    }
    

    或者如果您的 /var/www/b 是唯一的 PHP 应用程序,您可以向 PHP 处理程序添加一个 root 指令:

    server {
        listen 443 ...
    
        index index.php index.html;
        server_name domain.com;
        root /var/www/a;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location /b/ {
            root /var/www;
            try_files $uri $uri/ /b/index.php?$query_string;
        }
    
        location ~ \.php$ {
            root /var/www;
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.0-fpm.sock;
        }
    }
    
  2. 使用 map 指令从请求 URI 获取您的网络根目录:

    map $uri $root {
        ~^/b/    /var/www;
        default  /war/www/a;
    }
    server {
        listen 443 ...
    
        index index.php index.html;
        server_name domain.com;
        root $root;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location /b/ {
            try_files $uri $uri/ /b/index.php?$query_string;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.0-fpm.sock;
        }
    }