You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx多Location块与try_files配置问题:跨域名共享目录资源失败求助

Nginx多Location块与try_files配置问题:跨域名共享目录资源失败求助

Hi there! Let's troubleshoot those annoying 404 errors you're getting when trying to share pics and docs across your domains—this is a common Nginx config gotcha, so we'll get it sorted quickly.

The Root Cause

The issue here is how Nginx handles the root directive inside your location blocks. When you use root /home/admin/domain1.com; for /pics/, Nginx tries to look for files at /home/admin/domain1.com/pics/house.jpg (it appends the matched location path to the root you specified). But based on your setup, those folders are actually inside domain1's document root—likely /home/admin/domain1.com/html/pics/ (matching domain2's structure). That mismatch is why you're hitting 404s.

alias is designed exactly for cases where you need to map a location path to a different directory structure—it replaces the matched location part with the path you specify, instead of appending it. Update your domain2 config like this:

root /home/admin/domain2.com/html;
index index.php index.html;

location /pics/ {
    alias /home/admin/domain1.com/html/pics/;
    # Optional: Add caching headers for static files
    expires 30d;
    add_header Cache-Control "public, no-transform";
}

location /docs/ {
    alias /home/admin/domain1.com/html/docs/;
}

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

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

Fix 2: Adjust the root Path

If you prefer to stick with root, just point it to domain1's actual document root instead of the parent folder. This way, Nginx appends the /pics/ path correctly:

location /pics/ {
    root /home/admin/domain1.com/html;
}

location /docs/ {
    root /home/admin/domain1.com/html;
}

Quick Post-Fix Checks

  • Permissions: Make sure the Nginx runtime user (usually www-data) has read access to domain1's pics and docs folders. Run these commands to fix permissions if needed:
    chown -R www-data:www-data /home/admin/domain1.com/html/pics /home/admin/domain1.com/html/docs
    chmod -R 755 /home/admin/domain1.com/html/pics /home/admin/domain1.com/html/docs
    
  • Reload Nginx: After updating the config, always validate it first:
    sudo nginx -t
    
    If no errors pop up, reload the service to apply changes:
    sudo nginx -s reload
    

That should get your cross-domain file sharing working as expected!

备注:内容来源于stack exchange,提问作者Rad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 09:44:52