nginx 80端口配置多个location无效访问404问题

 更新时间:2024年06月20日 09:52:21   作者:风间琉璃c  

这篇文章主要介绍了nginx 80端口配置多个location无效访问404问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

目录
  • nginx 80端口配置多个location无效 访问404
    • 文件目录
    • nginx配置
    • 最基本的区别
  • nginx在location配置访问控制不起作用
    • 环境描述
    • 问题描述
    • 解决
  • 总结

    nginx 80端口配置多个location无效 访问404

    文件目录

    nginx配置

    一直感觉配置没啥问题,但是实际访问一直报404,很纳闷,百度了下发现又是一个知识盲区:

    alias与root的用法区别 alias实现虚拟目录

    最基本的区别

    alias指定的目录是准确的

    root是指定目录的上级目录,并且该上级目录要含有location指定名称的同名目录。

    一般情况下,在nginx配置中的良好习惯是:

    • 1)在location /中配置root目录;
    • 2)在location /path中配置alias虚拟目录。

    root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上。

    root的处理结果是:root路径+location路径

    配置为root html/manager,实际访问www.xxx.com/manager时,处理结果为:

    "www.xxx.com/manager" + "/manager" = "www.xxx.com/manager/manager"

    因此,一直报404错误!

    alias的处理结果是:使用alias路径替换location路径

    处理结果即为 www.xxx.com/manager,因此能访问到。

    所以,html/manager目录结构的正确nginx配置应该为(使用alias):

    或(使用root):

    nginx在location配置访问控制不起作用

    环境描述

    nginx nginx/1.12.2
    涉及nginx模块 –without-http_access_module
    linux CentOS Linux release 7.6.1810 (Core)
    使用vmware虚拟机作为服务器
    Syntax: allow address | CIDR | unix: | all;
    Default:
    Context: http, server, location, limit_except
    Syntax: deny address | CIDR | unix: | all;
    Default:
    Context: http, server, location, limit_except

    问题描述

    在配置nginx限制ip访问时发现配置不起作用,限制的ip仍旧可以访问,location配置如下

    location ~ ^/admin.html {
    root /opt/app/code;
    allow all;
    
    deny 192.168.136.1;
    index index.html index.htm;
    }

    配置完成后,发现使用192.168.136.1主机仍然可以访问,如下图

    解决

    查看官网可知

    The rules are checked in sequence until the first match is found. In this example, access is allowed only for IPv4 networks 10.1.1.0/16 and 192.168.1.0/24 excluding the address 192.168.1.1, and for IPv6 network 2001:0db8::/32. In case of a lot of rules, the use of the ngx_http_geo_module module variables is preferable.

    他会依次检查规则,直至找到第一个匹配项,也就是说如果匹配第一个,就不会再往后面找了

    经测试发现,allow或者deny中有指定限制具体ip的放在上面即可,如上解决配置

    location ~ ^/admin.html {
    root /opt/app/code;
    
    deny 192.168.136.1;
    allow all;
    index index.html index.htm;
    }

    如果配置的只允许某ip访问,如果无法限制,也是同样的问题。

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持小闻网。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。