Reputation: 1
Can someone help me for my nginx rewrite rule. I have the problem like this
if file not found in www.abc.com/name_dir/* it will redirect to www.abc.com/name_dir/index.php .
for example : not found in www.abc.com/xxx/* redirect to www.abc.com/xxx/index.php not found in www.abc.com/yyy/* redirect to www.abc.com/yyy/index.php not found in www.abc.com/zzz/* redirect to www.abc.com/zzz/index.php not found in www.abc.com/kk/* redirect to www.abc.com/kkk/index.php ... the problem i have thousand of name_dir. I have nginx.conf like this
if (-f $request_filename) {
break;
}
if (-d $request_filename) {
rewrite (^.+$) $1/
break;
}
if (!-e $request_filename) {
rewrite ^/xxx/(.*)$ /xxx/index.php?$1 last;
rewrite ^.+?(/.*\.php)$ $1 last;
}
In configuration above only redirect name_dir xxx. How rewrite rule to redirect all directory ? Thank for your help
Upvotes: 0
Views: 3147
Reputation: 1693
You want to use try_files to check for the existence of files instead of if statements here (because If's are Evil in Nginx).
To to a single directory, it would be like:
location /xxx/{
try_files $uri $uri/ /xxx/index.php;
index index.php
}
What this does is try the uri as a file first. If that doesn't work, it'll try as a directory. If neither work, it'll default to index.php of /xxx/. The extra index line is to keep it from showing a blank page if you go directly to whatever.com/xxx
Using regex, we can expand this rule to work with more than one directory:
location ~* ^(/.*)/{
try_files $uri $uri/ $1/index.php?$uri&$args;
index index.php
}
This should grab the full directory structure and rout it to the appropriate index.
If you only wanted the second example to go to yyy/index.php, use this regex in the location instead:
^(/.*?)/
Upvotes: 2