Nginx – Rewrite a subdirectory to root on nginx

nginxrewrite

let's say I have a site http://domain/ and I put some files in a subdirectory /html_root/app/ and I use the following rewrite rule to rewrite this folder to my root:

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;
}

I know this is not a clever way becase I have another subdirectory /html_root/blog/ and I want it can be accessed by http://domain/blog/.

My problem is, the above rewrite rule works ok but still have some issues: If I access

http://domain/a-simple-page/ (It's rewrited from http://domain/app/a-simple-page/)

it works fine, but if I access

http://domain/a-simple-page (without trailing slash), it redirects to original address:

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

Any way to redirect the URL without trailing-slash follow my rule?

Best Answer

Classic case of following a down right wrong tutorial instead of reading the wiki I highly suggest reading about the features you (should) use (such as location and try_files) as well as my Nginx primer as you completely miss the basics of Nginx.

I have made an attempt to write what you want in a proper format but I cannot promise it'll work as I'm not sure I actually understand what you're trying to do, nevertheless, it should give you a basis to start from.

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?;
    }
}