如何在Nginx中将子域名网站配置为主域名下的路径形式?
解决Nginx子域名转主域名路径的404问题
你的配置里存在关键错误:server_name字段仅用于匹配域名,不能包含路径,xyz.example.io/.*这种写法完全无效,这是配置不生效的核心原因。要实现主域名路径映射(如www.example.io/name),需要针对每个路径单独配置location块,以下是完整的解决方案:
核心配置思路
假设你要将原子域名站点分别映射到www.example.io/app1、www.example.io/app2,各自的根目录为/home/ubuntu/www/app1、/home/ubuntu/www/app2,主站点根目录保留为/home/ubuntu/www/landing_frontend,配置示例如下:
server { listen 80; listen [::]:80; # 仅保留主域名,无需子域名或路径 server_name www.example.io example.io; # 主站点根目录 root /home/ubuntu/www/landing_frontend; index index.html index.php; # 映射/app1路径到对应站点 location /app1 { # 用alias替换路径前缀,指向实际站点目录 alias /home/ubuntu/www/app1; index index.html index.php; # 静态文件找不到时,转发到/app1下的index.php try_files $uri $uri/ /app1/index.php?$args; # 处理/app1下的PHP请求 location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; # 使用$request_filename适配alias路径,避免文件定位错误 fastcgi_param SCRIPT_FILENAME $request_filename; } } # 映射/app2路径到对应站点(结构同app1) location /app2 { alias /home/ubuntu/www/app2; index index.html index.php; try_files $uri $uri/ /app2/index.php?$args; location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $request_filename; } } # 保留原有的/scripts路径处理 location /scripts { try_files $uri $uri/ /index.php?$args; index index.html index.php; } # 主站点的PHP请求处理 location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; try_files $uri $uri/ /index.php?$args; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } }
关键注意事项
- alias vs root:用
alias而不是root,因为root会将路径前缀拼接在根目录后(比如root /app1会指向/home/ubuntu/www/landing_frontend/app1),而alias会直接替换路径前缀,准确指向目标站点目录。 - PHP路径适配:使用
alias时,必须将SCRIPT_FILENAME设为$request_filename,否则Nginx会错误拼接路径导致404。 - 静态文件与路由转发:
try_files指令确保静态文件存在时直接返回,不存在时转发到对应路径的入口文件(适配PHP框架或单页应用)。
单页应用简化配置
如果你的站点是Vue/React这类无PHP的单页应用,可简化对应location:
location /app1 { alias /home/ubuntu/www/app1; # 所有请求转发到index.html,适配前端路由 try_files $uri $uri/ /app1/index.html; }
生效步骤
- 执行
nginx -t检查配置语法是否正确 - 语法无误后执行
systemctl reload nginx重启Nginx - 确保各站点目录权限正确,Nginx进程拥有读取权限
内容的提问来源于stack exchange,提问作者Marcel
相关产品推荐
相关产品推荐

