简体   繁体   中英

rewrite rule nginx

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

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.

  • abc.com/yyy/nonexistant.php ==> abc.com/yyy/index.php
  • abc.com/yyy/zzz/nonexistant.php ==> abc.com/yyy/zzz/index.php

If you only wanted the second example to go to yyy/index.php, use this regex in the location instead:

^(/.*?)/

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