简体   繁体   中英

Nginx rewrite a folder with exclude

i am working on nginx webserver.

I want to redirect all urls inside folder1 www.site.com/folder1/ but not the subfolder1 www.site.com/folder1/subfolder1

I created these rules to nginx configuration but no luck.

location = /folder/subfolder {

}

location /folder {

rewrite ^/folder(.*) www.redirect.com permanent;

}

Am i missing something?

Ok so here's a refined answer including some of the comments I've read plus one of mine,
to be able to access the assets inside the subfolder I added the try_files , and the 301 redirect in all other urls was added for the redirection.

location /folder/subfolder {
    try_files $uri $uri/ =404;
}

location /folder {
    return 301 $scheme://example.com;
}

Your new set of rules should be as follows. I am assuming that valid file hits are okay (ie the user knew the file). If you do not want this behaviour, replace try_files with the content of the @rw block:

location /folder {
    try_files $uri $uri/ @rw;
}
location @rw {
    rewrite ^/folder/([^\/]*) http://www.redirect.com/ permanent;
}

These should work.

Remove the "=" because that's for "exact" match. So it only matches the folder itself, and a request for "/folder/subfolder/a_file.html" won't match that block. Also you need to add $scheme in your rewrite rule. And if you just want to redirect to the home page ( http://www.redirect.com ), you can remove the "$1" part.

location /folder/subfolder {

}

location /folder {

  rewrite ^/folder(.*)$ $scheme://www.redirect.com$1 permanent;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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