2013-06-23 49 views
1

我想使用名稱作爲url,像stackoverflow。我有一個godaddy的Linux主機,並使用.htaccess來控制mod_rewrite網址。.htaccess和mod_rewrite - 不能得到它的工作

我試圖得到如下:

  • /約=> about.php
  • /學校/加=>附加school.php
  • /API /問題/問= > /questions.php?action=ask
  • /API /問題/ 158 => /questions.php?action=get & ID = 158
  • /API /問題/ 144 /分=> /questions.php? action = get-points & id = 144

這是我迄今爲止,它不工作:

## Mod rewrite manual: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html 
<IfModule mod_rewrite.c> 
    RewriteEngine On 

    # try the corresponding php file 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ([A-Za-z0-9_-]+) $1.php [qsa] 

    # special cases 
    RewriteRule ^schools\/add$ add-school.php 

    # API 
    RewriteRule ^api\/questions\/ask$ "api.php?action=ask" [qsa] 
    RewriteRule ^api\/questions\/(\d+)$ "api.php?action=get&id=$1" [qsa] 
    RewriteRule ^api\/questions\/(\d+)\/points$ "api.php?action=get-points&id=$1" [qsa] 

</IfModule> 
+1

哪些規則是沒有工作,你爲什麼要引用過去的3個重定向? – jeroen

+0

沒有規則適用於我。我引用它來試圖使其工作。 –

+2

您的第一個抓包塊可能優先。使用'RewriteLog'找出。是的,引號是無效的,'\ /'斜槓逃脫多餘的順便說一句。 – mario

回答

1

代碼中有幾處錯誤:

  1. 重寫規則排序非常重要。你應該總是從最具體的到最通用的。記住通用的可以匹配特定規則的模式並覆蓋這些特殊情況。
  2. 始終用L(上一個)標記規則的單獨結尾。
  3. 轉發請求到.php您需要確保php文件實際存在。

隨着這裏的建議是你修改後的代碼:

Options +FollowSymLinks -MultiViews 

<IfModule mod_rewrite.c> 
    # Turn mod_rewrite on 
    RewriteEngine On 
    RewriteBase/

    # special cases 
    RewriteRule ^schools/add/?$ /add-school.php [L,NC] 

    # API 
    RewriteRule ^api/questions/ask/?$ /api.php?action=ask [L,QSA,NC] 
    RewriteRule ^api/questions/(d+)/points/?$ /api.php?action=get-points&id=$1 [L,QSA,NC] 
    RewriteRule ^api/questions/(d+)/?$ /api.php?action=get&id=$1 [L,QSA,NC] 

    # try the corresponding php file if it exists 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f 
    RewriteRule ^(.+?)/?$ $1.php [L] 
</IfModule> 
1

所以你的第一個規則被接管。當你去學校/添加和文件不存在它重定向你schools.php也不存在,所以你只需要重新排序它們,而我們在它的時候刪除轉義:

## Mod rewrite manual: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html 
<IfModule mod_rewrite.c> 
    RewriteEngine On 

    # special cases 
    RewriteRule ^schools/add$ add-school.php 

    # API 
    RewriteRule ^api/questions/ask$ api.php?action=ask [qsa] 
    RewriteRule ^api/questions/(d+)$ api.php?action=get&id=$1 [qsa] 
    RewriteRule ^api/questions/(d+)/points$ api.php?action=get-points&id=$1 [qsa] 


    # try the corresponding php file 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ([A-Za-z0-9_-]+) $1.php [qsa] 
</IfModule>