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

想让不同的 URL 返回同一个页面应该怎么配置?

  •  
  •   lxy · 2017-10-13 12:14:13 +08:00 · 2257 次点击
    这是一个创建于 2384 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现有如下配置(省略其它)

    location ~* /user/view/\d+/$ {
        alias /path/to/dist/view/;
        index user_view.html;
        default_type "text/html";
    }
    
    location / {
        root /path/to/dist/;
        index  index.html index.htm;
        default_type "text/html";
        try_files $uri.html $uri $uri/  =404;
    }
    

    预期是访问 localhost/user/view/123/ 时,应当返回我设置的 index 页面,即 /path/to/dist/view/目录下的 user_view.html。

    但结果是 404。

    打开 nginx debug 日志。摘要如下

    (前略)
    [debug] 4000#2380: *1 test location: "/"
    [debug] 4000#2380: *1 test location: ~ "/user/view/\d+/$"
    [debug] 4000#2380: *1 using configuration "/user/view/\d+/$"
    (中略)
    [debug] 4000#2380: *1 http script copy: "/path/to/dist/view/"
    [debug] 4000#2380: *1 open index "/path/to/dist/view/user_view.html"
    [debug] 4000#2380: *1 internal redirect: "/user/view/123/user_view.html?"
    [debug] 4000#2380: *1 rewrite phase: 1
    [debug] 4000#2380: *1 test location: "/"
    [debug] 4000#2380: *1 test location: ~ "/user/view/\d+/$"
    [debug] 4000#2380: *1 using configuration "/
    (后略)
    

    可以看到,先匹配到了正确的正则路径,而且 open index 也找到了我设置的默认页面,之后突然一个 internal redirect 重定向,最后匹配到不相关的 / 。

    实在搞不懂为什么……

    第 1 条附言  ·  2017-10-13 14:01:31 +08:00

    虽然不太明白。解决方法是放弃 index,直接 try_files 返回固定的 html 。

    location ~* /user/view/\d+/$ {
        alias /path/to/dist/view/;
        default_type "text/html";
        try_files user_view.html =404;
    }
    
    2 条回复    2017-10-13 13:40:03 +08:00
    gstqc
        1
    gstqc  
       2017-10-13 12:57:29 +08:00 via iPhone   ❤️ 1
    alias 使用正则的话,必须要捕获正则并用在 alias 中
    fenglangjuxu
        2
    fenglangjuxu  
       2017-10-13 13:40:02 +08:00
    加 break 试试
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5352 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 01:28 · PVG 09:28 · LAX 18:28 · JFK 21:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.