Nginx子文件夹location配置问题:访问/view路径出现404
/view Directory Let's break down what's going wrong with your current setup and how to fix it. First, here's your existing config for reference:
server { listen 80; server_name some-site.io; root /srv/projects/folder/public; location /view { try_files $uri /index.html =404; } }
The Root Cause
When you hit some-site.io/view, here's what Nginx does right now:
- It checks if
$uri(which is/view) exists as a file or directory in your root path (/srv/projects/folder/public). Since/viewis a directory, not a file, Nginx skips this step. - Next, it tries to load
/index.html—but this looks for the index file in your root directory, not inside the/viewsubfolder. Since that file doesn't exist there, you get a 404.
Two Simple Fixes
Option 1: Adjust try_files to Target the /view Index
Update your location /view block to explicitly look for the index file inside the /view directory, and also handle directory requests properly:
location /view { try_files $uri $uri/ /view/index.html =404; }
$uri/tells Nginx to treat/viewas a directory request- If the directory doesn't have an auto-indexed file, it falls back to
/view/index.html(which is exactly where your index file lives)
Option 2: Add an index Directive for Automatic Directory Indexing
If you want Nginx to automatically look for standard index files in the /view directory, add the index directive and tweak try_files:
location /view { index index.html index.htm; # Define default index files for the directory try_files $uri $uri/ =404; }
This way, when you access /view, Nginx will check for index.html (or index.htm) directly inside /srv/projects/folder/public/view and return it if it exists.
Quick Checks to Verify
- Double-check that
/srv/projects/folder/public/view/index.htmlactually exists (typos are a common culprit!) - Make sure the Nginx process has read permissions for that file and the
/viewdirectory
Either of these fixes should resolve the 404 error when accessing some-site.io/view, while still letting you load files like some-site.io/view/app.js correctly.
内容的提问来源于stack exchange,提问作者malcoauri

