| 
 
     
TA的每日心情  | 开心 2025-10-7 13:38 | 
|---|
 
  签到天数: 1664 天 [LV.Master]伴坛终老 
 | 
在Nginx中配置location的匹配规则时,相信大家都遇到过 URL 去掉末尾斜杠(/)匹配失败的情况。 
 
 
我们先来举例描述一下这个问题。 
 
 
example配置 
假设我们配置是这样:server { 
 
        listen 80 
 
        server_name xxx.com 
 
        ... 
 
        ... 
 
        location /yyy { 
 
            root /home/projects; 
 
                index  index.html index.htm; 
 
   } 
 
        ... 
 
        ... 
 
}  那么,如果我们访问 xxx.com/yyy/ ,会匹配到服务器上/home/projects/yyy文件夹,并打开index.html或者index.htm文件。 
 
 
而当我们访问 xxx.com/yyy ,你会发现,匹配失败 
 
 
这种情况下,你当然可以祈祷用户能够每次输入这个 URL 的时候都带上(/),但是说实在的,我估计你每次打开百度的时候都是直接输入 www.baidu.com 而不会加斜杠输入 www.baidu.com/ 。末尾斜杠显得如此多此一举。 
 
 
那如何才能解决这个问题呢? 
 
 
解决思路 
既然加了斜杠可以匹配,那么,我们就可以对不加斜杠的 URL 进行重写,给它加上末尾斜杠,然后重定向,不就解决问题了。 
 
 
这里,我们需要用到 Nginx 中 ngx_http_rewrite_module 这个 module。 
 
 
首先,我们判断请求资源是否是请求目录类型 
 
 
if ( -d $request_filename ) 
 
然后我们利用正则来匹配、替换,并用rewrite中permanent来重定向(301) 
 
rewrite ^/(.*)([^/])$ $scheme://$host/$1$2/ permanent;  正确配置 
修改配置如下server { 
 
        listen 80 
 
        server_name xxx.com 
 
        ... 
 
        ... 
 
        location /yyy { 
 
            root /home/projects; 
 
                   if ( -d $request_filename ){ 
 
                        rewrite ^/(.*)([^/])$ $scheme://$host/$1$2/ permanent; 
 
                } 
 
                index  index.html index.htm; 
 
   } 
 
        ... 
 
        ... 
 
}  然后验证配置是否有错误 
 
 
$ nginx -t  
 
如果没有语法错误,会提示 
 
 
/nginx.conf syntax is ok 
 
 
最后重启看效果 
 
 
$ nginx -s reload 
 
 |   
 
  
 |