NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
lxy
V2EX  ›  NGINX

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

  •  
  •   lxy · Oct 13, 2017 · 2681 views
    This topic created in 3159 days ago, the information mentioned may be changed or developed.

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

    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 重定向,最后匹配到不相关的 / 。

    实在搞不懂为什么……

    Supplement 1  ·  Oct 13, 2017

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

    location ~* /user/view/\d+/$ {
        alias /path/to/dist/view/;
        default_type "text/html";
        try_files user_view.html =404;
    }
    
    2 replies    2017-10-13 13:40:03 +08:00
    0ZXYDDu796nVCFxq
        1
    0ZXYDDu796nVCFxq  
       Oct 13, 2017 via iPhone   ❤️ 1
    alias 使用正则的话,必须要捕获正则并用在 alias 中
    keepfun
        2
    keepfun  
       Oct 13, 2017
    加 break 试试
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5337 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 01:17 · PVG 09:17 · LAX 18:17 · JFK 21:17
    ♥ Do have faith in what you're doing.