V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
qize0921
V2EX  ›  NGINX

求助: Nginx 配置 location 问题

  •  
  •   qize0921 · Dec 29, 2023 · 2067 views
    This topic created in 850 days ago, the information mentioned may be changed or developed.

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

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

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

    Supplement 1  ·  Jan 10, 2024

    最终解决方案:

    location ~ ^/test/(\d+)/ {
          rewrite ^/test/(\d+)/$ /test/index.html?id=$1 last;
    }
    
    location = /test/index.html {
        alias /www/demo/index.html;
    }
    
    7 replies    2024-01-01 20:08:14 +08:00
    edotac
        1
    edotac  
       Dec 29, 2023
    Nginx 这么配置
    ```
    location /test/ {
    alias /www/demo/;
    index index.html;
    }
    ```
    在前端项目中设置 id 的路由匹配,比如 vue 中的 vuerouter
    vampuke
        2
    vampuke  
       Dec 29, 2023
    location ~ ^/test/(\d+)/$
    beyondstars
        3
    beyondstars  
       Dec 29, 2023
    要通过正则表达式匹配路径,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
       Dec 29, 2023
    @vampuke
    @beyondstars

    我看两位给的解决方案都差不多,但是我都测试了下,访问还是 404 ,无法匹配到路径,但是我去掉正则,就单匹配 /test/就正常了。不知道是哪里的原因。
    qize0921
        5
    qize0921  
    OP
       Dec 29, 2023
    @edotac 就一个单页面,没有用到框架
    sparkssssssss
        6
    sparkssssssss  
       Dec 29, 2023
    /www/demo 去掉/试试
    julyclyde
        7
    julyclyde  
       Jan 1, 2024
    @qize0921 可以开 error_log 详细级别看一下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   961 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 20:49 · PVG 04:49 · LAX 13:49 · JFK 16:49
    ♥ Do have faith in what you're doing.