在nginx上重写一个子目录到root

spa*_*oid 4 rewrite nginx

假设我有一个站点http://domain/,我将一些文件放在一个子目录中/html_root/app/,我使用以下重写规则将此文件夹重写到我的根目录:

location / {
    root /html_root;
    index index.php index.html index.htm;

    # Map http://domain/x to /app/x unless there is a x in the web root.
    if (!-f $request_filename){
        set $to_root 1$to_root;
    }
    if (!-d $request_filename){
        set $to_root 2$to_root;
    }
    if ($uri !~ "app/"){
        set $to_root 3$to_root;
    }
    if ($to_root = "321"){
        rewrite ^/(.+)$ /app/$1;
    }

    # Map http://domain/ to /app/.
    rewrite ^/$ /app/ last;
}
Run Code Online (Sandbox Code Playgroud)

我知道这不是一个聪明的方法,因为我有另一个子目录/html_root/blog/并且我希望它可以通过http://domain/blog/.

我的问题是,上面的重写规则可以正常工作,但仍然存在一些问题:如果我访问

http://domain/a-simple-page/(改写自http://domain/app/a-simple-page/

它工作正常,但如果我访问

http://domain/a-simple-page (没有尾部斜杠),它重定向到原始地址:

http://domain/app/a-simple-page/,

任何不带斜杠的重定向 URL 的方法都遵循我的规则吗?

Mar*_*ald 5

遵循正确错误教程而不是阅读 wiki 的经典案例我强烈建议阅读有关您(应该)使用的功能(例如位置和 try_files)以及我的 Nginx 入门,因为您完全错过了 Nginx 的基础知识。

我已尝试以适当的格式编写您想要的内容,但我不能保证它会起作用,因为我不确定我是否真正理解您要做什么,但是,它应该为您提供一个基础.

server {
    listen 80;
    server_name foobar;

    root /html_root;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ @missing;
    }

    location /app {
        # Do whatever here or leave empty
    }

    location @missing {
        rewrite ^ /app$request_uri?;
    }
}
Run Code Online (Sandbox Code Playgroud)