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

求助: Nginx 配置 location 问题

  •  
  •   qize0921 · 119 天前 · 1081 次点击
    这是一个创建于 119 天前的主题,其中的信息可能已经有所发展或是发生改变。

    由于有个参数是数字,还是动态的,所以我的预期是想达到类似下面这种(随便写的):

    location /test/(\d+)/ {
        	alias   /www/demo/;
            index  index.html;
    }
    

    目前情况是,不能通过 ? 拼接参数,所以只能放到 url 里面了。然后网上找了很多例子也自己调试了很多次,都是无法生效。有没有懂的大佬,麻烦指点一下,谢谢!

    第 1 条附言  ·  107 天前

    最终解决方案:

    location ~ ^/test/(\d+)/ {
          rewrite ^/test/(\d+)/$ /test/index.html?id=$1 last;
    }
    
    location = /test/index.html {
        alias /www/demo/index.html;
    }
    
    7 条回复    2024-01-01 20:08:14 +08:00
    edotac
        1
    edotac  
       119 天前
    Nginx 这么配置
    ```
    location /test/ {
    alias /www/demo/;
    index index.html;
    }
    ```
    在前端项目中设置 id 的路由匹配,比如 vue 中的 vuerouter
    vampuke
        2
    vampuke  
       119 天前
    location ~ ^/test/(\d+)/$
    beyondstars
        3
    beyondstars  
       119 天前
    要通过正则表达式匹配路径,location 后面应以 ~ 或者 ~* 开头,其中 ~* 是 case-insensitive 的(不区分大小写)。

    试试

    ```
    location ~ ^/test/(\d+)$ {
    # 你的其它内容
    }
    ```

    详见

    - 官方 doc: https://nginx.org/en/docs/http/ngx_http_core_module.html#location
    - nginx 匹配测试: https://nginx.viraptor.info/
    qize0921
        4
    qize0921  
    OP
       119 天前
    @vampuke
    @beyondstars

    我看两位给的解决方案都差不多,但是我都测试了下,访问还是 404 ,无法匹配到路径,但是我去掉正则,就单匹配 /test/就正常了。不知道是哪里的原因。
    qize0921
        5
    qize0921  
    OP
       119 天前
    @edotac 就一个单页面,没有用到框架
    coolloves
        6
    coolloves  
       119 天前
    /www/demo 去掉/试试
    julyclyde
        7
    julyclyde  
       116 天前
    @qize0921 可以开 error_log 详细级别看一下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2817 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 06:17 · PVG 14:17 · LAX 23:17 · JFK 02:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.