2015-02-12 21 views
0

我在Yii2應用.htaccess的URL重寫Yii2應用

http://127.0.0.1/frontend/web/index.php?r=site%2Flogin 
http://127.0.0.1/frontend/web/index.php?r=site%2Fpage2 
http://127.0.0.1/frontend/web/index.php?r=site%2Fsample 
http://127.0.0.1/frontend/web/index.php?r=site%2Fsignup 

以下網址結構我怎麼能轉換這個URL類似

http://127.0.0.1/login.php 
http://127.0.0.1/page2.php 
http://127.0.0.1/sample.php 
http://127.0.0.1/signup.php 

我應該刪除frontend/web/index.php?r=site%2F

我嘗試過,但它不起作用

Options -Multiviews 

RewriteEngine On 
RewriteBase/

# Force search engines to use http://127.0.0.1/frontend/web/ 
RewriteCond %{HTTP_HOST} !^http://127\.0\.0\.1/frontend/web/$ 
RewriteRule ^(.*) http://127.0.0.1/frontend/web/$1 [R=301,L] 

# Specify search friendly URLs 
RewriteRule ^login\.php$ /index.php?r=site%2Flogin [L] 

我也試過了,它也沒有工作。

RewriteEngine on 
RewriteRule ^frontend/web/index.php?r=site%2F([^\./]+) /$1.php [L] 
+0

你想在全局中添加'.php'後綴還是僅僅爲'SiteController'操作? – arogachev 2015-02-12 09:39:53

+0

@arogachev - 全局通過htaccess – lock 2015-02-12 09:40:29

+0

而您想爲'SiteController'操作移除'site',對吧? – arogachev 2015-02-12 09:41:11

回答

1

無需更改.htaccess即可實現此目的。調整urlManager組件。 添加到您的應用程序配置:

'components' => [ 
    'urlManager' => [ 
     'enablePrettyUrl' => true, // Cancel passing route in get 'r' paramater 
     'showScriptName' => false, // Remove index.php from url 
     'suffix' => '.php', // Add suffix to all routes (globally) 
    ], 
    // Compare requested urls to routes 
    'rules' => [ 
     'login' => 'site/login', 
     'page2' => 'site/page2', 
     'sample' => 'site/sample', 
     'signup' => 'site/signup', 
    ], 
], 

至於其他所有航線除控制器部分 - 它違反了MVC的關鍵概念。

如何定義哪個控制器請求的操作屬於這種情況?

什麼情況下的行爲具有相同的名稱?

例如:http://127.0.0.1/create.php - 應該加載site/create還是users/create

另外我不確定這是否是好的做法,但是您可以使用規則以相同方式對所有路線進行比較,但所有操作名稱都應該是唯一的。

結論:如上所述,您可以將url修改爲所需的視圖,但僅建議將缺省控制器名稱用於默認控制器(SiteController)。

正式文件:

+0

在'public function actions()'中的'frontend/controllers/sitecontroller.php'下,我確實保留了這段代碼,並沒有幫助。仍然我無法通過'domain/login.php'調用其他的URL。 – lock 2015-02-12 10:11:51

+0

根據你的模板(基本/高級),你應該像上面提到的那樣將它放在應用程序配置中。 'actions()'用於完全不同的目的。 – arogachev 2015-02-12 10:12:56

+0

我正在使用高級應用程序,並且在組件內的前端> config> main.php中,我粘貼了您的代碼,但仍然無法作爲域/登錄進行調用。php – lock 2015-02-12 10:20:06