具有不同根的 Nginx 多个位置 [英] Nginx multiple locations with different roots

查看:48
本文介绍了具有不同根的 Nginx 多个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 nginx 配置,里面有 3 个位置.他们每个人都有自己的根目录+我将来应该可以轻松添加另一个.

I have really simple nginx configuration with 3 locations inside. Each of them have it's own root directory + I should be able to add another in the future easily.

我想要的:

请求 /admin => 位置 ^/admin(/|$)

请求 /admin/ => 位置 ^/admin(/|$)

请求 /admin/blabla => 位置 ^/admin(/|$)

请求/client => location ^/client(/|$)

Request /client => location ^/client(/|$)

请求 /client/ => location ^/client(/|$)

Request /client/ => location ^/client(/|$)

请求 /client/blabla => 位置 ^/client(/|$)

请求 /blabla => 位置 /

请求 /admin-blabla => 位置 /

请求 /client-blabla => 位置 /

实际结果:

所有请求都转到位置 /.

All requests goes to location /.

我使用别名、try_files、roots 和正则表达式的不同组合尝试了来自文档、stackoverflow 和其他来源的许多不同建议,但没有任何效果对我有用.

I tried many different suggestions from docs, stackoverflow and other sources using different combinations of aliases, try_files, roots and regexes, but nothing worked for me.

仅当我尝试仅使用 return 200 'admin';return 200 'front' 时,它才按预期工作.

Only when I tried to use just return 200 'admin'; and return 200 'front' it worked as intended.

最小配置:

server {
    listen 80;
    index index.html;

    location / {
        root /var/www/html/www_new/front;
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/admin(/|$) {
        root /var/www/html/www_new/admin;
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/client(/|$) {
        root /var/www/html/www_new/client;
        try_files $uri $uri/ /index.html;
    }
}

目录结构:

  • /管理员
  • /客户端
  • /前面

谢谢

推荐答案

当您更改根目录时,它仍然会包含目录名称,因此您要做的只是将根目录设置为 location/.您也不需要在 /admin 上添加任何额外的正则表达式,因为位置修饰符 ~ 已经告诉 nginx '任何以'开头的内容.

When you change the root it'll still include the directory name, so what you want to do is only set the root for location /. You also don't need any additional regex on /admin as the location modifier ~ already tells nginx 'anything starting with'.

这适用于您的用例:

server {
    listen 80;
    index index.html;

    location / {
        root /var/www/html/www_new/front;
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/admin {
        root /var/www/html/www_new; # the directory (/admin) will be appended to this, so don't include it in the root otherwise it'll look for /var/www/html/www_new/admin/admin
        try_files $uri $uri/ /admin/index.html; # try_files will need to be relative to root
    }
}

这篇关于具有不同根的 Nginx 多个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆