第一步:通過Xshell在虛擬機中下載nginx
sudo apt-get install nginx
第二步:進入nginx配置頁面
cd /etc/nginx
我這里創建了一個html文件夾 在進入去創建頁面并且重新加載
boahu@boahu-VMware-Virtual-Platform:/$ cd /etc/nginx
boahu@boahu-VMware-Virtual-Platform:/etc/nginx$ ls
conf.d fastcgi_params koi-utf mime.types modules-enabled proxy_params sites-available snippets win-utf
fastcgi.conf html koi-win modules-available nginx.conf scgi_params sites-enabled uwsgi_params
boahu@boahu-VMware-Virtual-Platform:/etc/nginx$ cd html/
boahu@boahu-VMware-Virtual-Platform:/etc/nginx/html$ ls
myindex02.html myindex.html
boahu@boahu-VMware-Virtual-Platform:/etc/nginx/html$ sudo vi myindex03.html
boahu@boahu-VMware-Virtual-Platform:/etc/nginx/html$ ls
myindex02.html myindex03.html myindex.html
boahu@boahu-VMware-Virtual-Platform:/etc/nginx/html$ sudo nginx -s reload
2025/06/20 16:15:31 [notice] 14003#14003: signal process started
boahu@boahu-VMware-Virtual-Platform:/etc/nginx/html$
第三步配置 conf.d
boahu@boahu-VMware-Virtual-Platform:/etc/nginx/html$ cd ..
boahu@boahu-VMware-Virtual-Platform:/etc/nginx$ ls
conf.d fastcgi_params koi-utf mime.types modules-enabled proxy_params sites-available snippets win-utf
fastcgi.conf html koi-win modules-available nginx.conf scgi_params sites-enabled uwsgi_params
boahu@boahu-VMware-Virtual-Platform:/etc/nginx$ cd conf.d/
boahu@boahu-VMware-Virtual-Platform:/etc/nginx/conf.d$ ls
mynginx.conf
boahu@boahu-VMware-Virtual-Platform:/etc/nginx/conf.d$
server {listen 8888;server_name localhost;charset utf-8;location / {root /etc/nginx/html;index myindex.html;}# 修復的精確匹配location = /login/ {alias /etc/nginx/html/;# 方法1: 使用try_filestry_files /myindex02.html =404;# 方法2: 或者使用rewrite# rewrite ^ /myindex02.html last;}# 前綴匹配location ^~ /login/ {root /etc/nginx/html;index myindex03.html;}
}
# 精確匹配
curl http://localhost:8888/login/# 前綴匹配
curl http://localhost:8888/login/test# 根目錄
curl http://localhost:8888/
如果訪問`/login/test`,Nginx會嘗試尋找`/etc/nginx/html/login/test`文件,如果該文件不存在,且沒有啟用`autoindex`,就會返回404。
修復后
location ^~ /login/ {alias /etc/nginx/html/;try_files /myindex03.html =404;
}
解決方案
修改前綴匹配配置,使用?try_files
?指令直接返回目標文件:
server {listen 8888;server_name localhost;charset utf-8;location / {root /etc/nginx/html;index myindex.html;}# 精確匹配/login/ → 返回myindex02.htmllocation = /login/ {alias /etc/nginx/html/;try_files /myindex02.html =404;}# 修復后的前綴匹配location ^~ /login/ {# 方案1:使用alias + try_files(推薦)alias /etc/nginx/html/;try_files /myindex03.html =404;# 方案2:或者使用root + rewrite# root /etc/nginx/html;# rewrite ^/login/.*$ /myindex03.html last;}
}