1. 程式人生 > >nginx配置基於目錄的配置及地址重寫

nginx配置基於目錄的配置及地址重寫

htm rewrite 地址 ida 顯示 sha 系統框架 stc url地址

7、需求:公司要求系統重構,需要重新配置系統框架,架構如下 域名
www.lxp.com

目錄結構:發布目錄是 /alidata/txall 這個目錄,這個目錄裏邊有callback usercenter ordercenter marketcenter 每個目錄裏邊有其他的東西和一個web目錄,web目錄裏邊有index.php 或index.html,當訪問 www.lxp.com/callback 時直接訪問的是 callback下邊的web目錄,其他目錄都一樣的要求

這是現在的目錄架構,需求是,當訪問dev.shirbility.cn/callback 時 要定義到 callback/web這個目錄裏邊(有index.htnl或index.php) 當要訪問 callback 裏邊的其他目錄時也可以直接訪問。像其他的usercenter ordercenter marketcenter 也是同樣的需求,配置如下


server {
    listen 80;
    server_name  www.lxp.com;
    root  /alidata/txall;
    index index.html index.php;

     location   = /callback  {
     root  /alidata/txall/callback;
     index   index.html index.php index.htm;
     rewrite  "^(.*)/callback$"   /callback/web/ last;
     }

     location  = /usercenter {
     root  /alidata/txall/usercenter;
     index  index.html index.php index.htm;
     rewrite  "^(.*)/usercenter$"  /usercenter/web/ last;
     }

     location  = /ordercenter {
     root  /alidata/txall/ordercenter;
     rewrite  "^(.*)/ordercenter$"  /ordercenter/web/ last;
     index   index.html  index.php index.htm;
      }

     location  = /marketcenter {
    root  /alidata/txall/marketcenter;
    rewrite  "^(.*)/marketcenter$"  /marketcenter/web last;
    index    index.html index.php index.htm;
      }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

}

```
     location   = /callback  {
     root  /alidata/txall/callback;
     index   index.html index.php index.htm;
     rewrite  "^(.*)/callback$"   /callback/web/ last;
     }
```

我是直接重定向到 /callback/web/  裏邊。當web後邊沒有/時 如(/callback/web),你在訪問www.lxp.com/callback  的時候瀏覽器的url地址就會跳轉  成 www.lxp.com/callback/web/這樣,但是要求是能顯示跳轉,所以就加 /,這樣同時能夠訪問到callback目錄裏邊與web同級的其他目錄或文件。

問題:當你訪問www.lxp.com/callback 時可以但訪問到頁面,但是你訪問 www.lxp.com/callback/  時就不能訪問到

原因 :因為www.lxp.com/callback  和 www.lxp.com/callback/ 是不一樣的
兩個訪問的目錄是不一樣的。
```
        location = /aaa {
        root /usr/share/nginx/html/aaa;
        rewrite  "^(.*)/aaa$"  /aaa/ last;
        }
```

這樣配置的話,你訪問 www.123.com/aaa   和 www.123.com/aaa/ 是一樣的,因為他的root 是/aaa  他的rewrite之後的也是/aaa   所以沒影響

但是我們的配置是
     location   = /callback  {
     root  /alidata/txall/callback;
     index   index.html index.php index.htm;
     rewrite  "^(.*)/callback$"   /callback/web/ last;
     }

root 和 rewrite後邊的東西不一樣,www.lxp.com/callback 放問的是重定向後的內容,但是www.lxp.com/callback/  訪問的是root (/alidata/txall/callback) 是這個。所以當你後邊加 / 的時候就會報404錯誤。加入callback目錄下有index.html  或者 index.php 的時候就會直接訪問到此頁面。  

nginx配置基於目錄的配置及地址重寫