NGINX配置问题:不同Web路径映射至服务器目录失败
NGINX路径映射配置修正方案
你的配置无法正常工作主要有两个核心问题:一是try_files指令的跳转路径未适配alias规则,二是FastCGI的脚本路径参数配置错误。以下是修正后的完整配置:
server { server_name test.local; root /srv; index index.html index.php; location /site1/ { alias /srv/site_1/src/public/; try_files $uri $uri/ /site1/index.php?$args; location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $request_filename; include fastcgi_params; } } location /site2/ { alias /srv/site_2/; try_files $uri $uri/ /site2/index.php?$args; location ~ \.php$ { fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $request_filename; include fastcgi_params; } } }
关键修改说明
alias末尾加斜杠:确保/site1/这类路径映射时,不会出现路径拼接错误(比如避免把/site1/test.php解析成/srv/site_1/src/publictest.php)。try_files跳转路径修正:原配置中/index.php会指向全局root的/srv/index.php,改成/site1/index.php后,会先经过外层location的alias映射,正确指向对应目录下的入口文件。- 嵌套location处理php请求:把php解析逻辑放到嵌套location里,只有请求php文件时才转发到FastCGI,静态文件直接由NGINX返回,提升效率。
SCRIPT_FILENAME参数调整:使用$request_filename替代$realpath_root$fastcgi_script_name,alias规则下$request_filename已经是映射后的真实文件路径,不会出现路径拼接错误。
配置修改后,执行nginx -t检查语法,无错误后重启NGINX即可生效。
内容的提问来源于stack exchange,提问作者holden321
相关产品推荐
相关产品推荐

