You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Nginx配置多URL对应不同项目遇404错误求助

解决Nginx多URL映射不同PHP项目的404问题

我来帮你搞定这个Nginx的404问题!你要实现的是通过/test1/test2访问不同的PHP项目,核心问题应该是location块里的路径映射没配置对,导致Nginx找不到正确的PHP文件。下面给你一套完整的可运行配置,再拆解关键要点:

完整的Server配置

server {
    listen 80;
    listen [::]:80;
    root /var/www;
    index index.php index.html index.htm;
    server_name 192.168.15.92 localhost; # 加上localhost,确保访问localhost时能匹配到这个server块

    # 处理/test1的请求
    location /test1 {
        # 先尝试匹配静态文件,找不到就转发到项目的index.php
        try_files $uri $uri/ /test1/index.php$is_args$args;

        # 嵌套处理PHP请求
        location ~ \.php$ {
            # 用alias替换路径前缀,把/test1/xxx.php映射到实际的/var/www/test-1/xxx.php
            alias /var/www/test-1;
            # 这里根据你的PHP版本调整socket路径,比如php7.4-fpm或php8.1-fpm
            fastcgi_pass unix:/run/php/php8.2-fpm.sock;
            fastcgi_index index.php;
            # 传递正确的文件路径给PHP-FPM
            fastcgi_param SCRIPT_FILENAME $request_filename;
            include fastcgi_params;
        }
    }

    # 处理/test2的请求,逻辑和test1一致
    location /test2 {
        try_files $uri $uri/ /test2/index.php$is_args$args;

        location ~ \.php$ {
            alias /var/www/test-2;
            fastcgi_pass unix:/run/php/php8.2-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            include fastcgi_params;
        }
    }
}

关键配置说明

  • 为什么用alias而不是root:你的项目目录是test-1(带横杠),但URL前缀是test1(无横杠),用root会把请求路径拼接成/var/www/test1/xxx.php,自然找不到文件;而alias会直接把/test1前缀替换成/var/www/test-1,路径就对了。
  • try_files的作用:先检查请求的静态文件是否存在(比如图片、CSS),如果不存在就转发到项目的index.php,避免直接访问非PHP路径返回404。
  • fastcgi_param SCRIPT_FILENAME:必须设置为$request_filename,结合alias才能把正确的文件路径传递给PHP-FPM,不然PHP会找不到要执行的脚本。

验证和重启步骤

  1. 测试配置是否合法:
sudo nginx -t
  1. 重启Nginx生效:
sudo systemctl restart nginx
  1. 检查文件权限(避免Nginx读不到文件):
sudo chown -R www-data:www-data /var/www/test-1 /var/www/test-2

内容的提问来源于stack exchange,提问作者Vestibule

火山引擎 最新活动