美文网首页Nginx高端成长之路服务端相关
解决Nginx中location匹配不到末尾不加斜杠的URL

解决Nginx中location匹配不到末尾不加斜杠的URL

作者: Quenice | 来源:发表于2018-09-18 23:44 被阅读5次

Nginx中配置location的匹配规则时,相信大家都遇到过 URL 去掉末尾斜杠(/)匹配失败的情况。

我们先来举例描述一下这个问题。

example配置

假设我们配置是这样:

server {
    listen 80
    server_name xxx.com
    ...
    ...
    location /yyy {
        root /home/projects;
        index  index.html index.htm;
   }
    ...
    ...
}

那么,如果我们访问 http://xxx.com/yyy/ ,会匹配到服务器上/home/projects/yyy文件夹,并打开index.html或者index.htm文件。

而当我们访问 http://xxx.com/yyy ,你会发现,匹配失败

这种情况下,你当然可以祈祷用户能够每次输入这个 URL 的时候都带上(/),但是说实在的,我估计你每次打开百度的时候都是直接输入 http://www.baidu.com 而不会加斜杠输入 http://www.baidu.com/ 。末尾斜杠显得如此多此一举。

那如何才能解决这个问题呢?

解决思路

既然加了斜杠可以匹配,那么,我们就可以对不加斜杠的 URL 进行重写,给它加上末尾斜杠,然后重定向,不就解决问题了。

这里,我们需要用到 Nginx 中 ngx_http_rewrite_module 这个 module。

首先,我们判断请求资源是否是请求目录类型

if ( -d $request_filename )

然后我们利用正则来匹配、替换,并用rewritepermanent来重定向(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

相关文章

网友评论

    本文标题:解决Nginx中location匹配不到末尾不加斜杠的URL

    本文链接:https://www.haomeiwen.com/subject/nkfbnftx.html