简体   繁体   English

Nginx 重写目录并排除子目录

[英]Nginx rewrite directory and exclude a subdirectory

This is my current nginx config file.这是我当前的 nginx 配置文件。

server {
    listen 6063;

    root /var/www/html/project;
    index index.php;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.2-fpm-backend.sock;
    }    

    rewrite ^/admin/(.*)$ /admin/index.php break;
}

Any access to /admin will rewrite to /admin/index.php.对 /admin 的任何访问都将重写到 /admin/index.php。

Now for some reasons I have to add css folder, js folder to /var/www/html/project/admin/includes.现在由于某些原因,我必须将 css 文件夹、js 文件夹添加到 /var/www/html/project/admin/includes。

So the new requires is any access to /admin/includes/* will access the real files for css and js.所以新的要求是对 /admin/includes/* 的任何访问都将访问 css 和 js 的真实文件。 All other access /admin/* (not /admin/includes) will rewrite to /admin/index.php.所有其他访问/admin/*(不是/admin/includes)将重写到/admin/index.php。

Or I can say any access to folder /admin if doesn't exists (like /admin/includes/css/example.css), then rewrite to /admin/index.php或者我可以说任何对文件夹 /admin 的访问(如果不存在)(如 /admin/includes/css/example.css),然后重写为 /admin/index.php

Thanks,谢谢,

OK, I found the answer.好的,我找到了答案。

location /admin {
    if (!-e $request_filename) {
        rewrite (.*)$ /admin/index.php last;
    }
}

If any access to folder /admin which doesn't exists ( it is not a real file like css or js files) will rewrite to /admin/index.php.如果对不存在的文件夹 /admin 的任何访问(它不是像 css 或 js 文件这样的真实文件)将重写到 /admin/index.php。

Nginx uses the longest matching location ( see docs ), so it's enough to give a more specific location directive: Nginx 使用最长的匹配位置( 参见文档),因此提供更具体的位置指令就足够了:

server {
    …

    location ~ /admin/css {
    }

    location ~ /admin {
       rewrite (.*)$ /admin/index.php last;
    }
}

Then, if anything matches /admin/css , it will process only the empty block (and so get served by default), and all that matches /admin (and not /admin/css ) will hit the rewrite.然后,如果有任何匹配/admin/css ,它将只处理空块(因此默认提供服务),并且所有匹配/admin (而不是/admin/css )将命中重写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM