V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
hayao650
V2EX  ›  NGINX

nginx location 配置问题

  •  
  •   hayao650 · 2016-02-04 14:32:12 +08:00 · 3571 次点击
    这是一个创建于 2997 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我现在想配置 nginx 实现以下需求:
    1 、主页通过 nginx 直接访问一个静态页面,静态页面目录是:/www/main/index.html
    2 、其他服务接口通过 nginx 代理,转发给后端的 python 服务,端口是 20002

    我现在的想法是通过两个 location 配置实现,但是在折腾了半天,也没有折腾出来,求各位前辈、高手给指点指点

    append:
    location = / {
    root /www/main;
    index index.html;
    }
    location / {
    proxy_pass http://xx.xx.xx.xx:20002;
    }
    我现在这种写法一直不能实现,我对这种写法的理解是,当我访问首页www.xxx.com的时候,nginx通过精确匹配,找到第一个location,
    当我访问www.xxx.com/xxx的时候,nginx找到第二个location,
    但是这样配置的话,首页无法访问
    第 1 条附言  ·  2016-02-04 15:12:59 +08:00
    我在单独写这两个 location 的一个时,都能正常访问,但是放在一起就不能访问,我感觉两个应该没有重复啊,我访问首页 www.xxx.com 的时候,应该是精确匹配到第一个 location ,访问 www.xxx.com/xxx 的时候没有匹配到,最后由第二个 location 处理
    7 条回复    2016-02-04 16:18:39 +08:00
    lecher
        1
    lecher  
       2016-02-04 15:27:18 +08:00 via Android
    location / {
    if (!-e $request_filename) {
    proxy_pass http://xx.xx.xx.xx:20002;
    }
    index index.html index.htm;
    }

    if 的判断是,如果指定路径不存在文件,则执行判断内的语句,将请求转发给代理端口。
    hayao650
        2
    hayao650  
    OP
       2016-02-04 15:30:44 +08:00
    @lecher 非常感谢,用了你的方法成功了,但是我还是不能理解,我的写法为什么不成功
    lution
        4
    lution  
       2016-02-04 15:41:24 +08:00
    用 try_files 试试

    rewrite ^/$ /index.html redirect;

    location / {
    root /www/main;
    try_files $uri @python_proxy;
    }

    location @python_proxy {
    proxy_pass http://127.0.0.1:20002;
    }
    lecher
        5
    lecher  
       2016-02-04 15:50:42 +08:00 via Android
    @hayao650 因为你的正则没有指定起始和结束符,所以,实际上你写的两个正则匹配的结果是一样的。 Nginx 中要指定仅匹配 / 的正则写法是: ^/$强制限定只匹配 /。

    我这个写法是不太好维护的。不如看看 seki 给的连接,试试 try_files 的语法,这个可以方便你指派多个规则跳转到同一个代理端口。维护起来更省事一些。
    hayao650
        6
    hayao650  
    OP
       2016-02-04 15:59:32 +08:00
    OK ,谢谢各位了,学习了
    xujif
        7
    xujif  
       2016-02-04 16:18:39 +08:00 via iPhone
    ~才用正则,=应该是直接匹配的,再把,=/index.html 加上尝试下?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2719 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:31 · PVG 13:31 · LAX 22:31 · JFK 01:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.