2014-10-08 179 views
0

我想用一些RewriteRule s到變換:預防規則,htaccess的重寫規則衝突

這裏htaccess

<IfModule mod_rewrite.c> 
RewriteEngine On 
RewriteBase/
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /index.php?id=$1 [L] 
RewriteRule ^(.*)/(.*)$ /index.php?id=$2&user=$1 [L] 
</IfModule> 

但似乎最後兩個規則不兼容:這種htaccess,我得到一些500 Internal Server Error

如何創建兩條規則,使它們不會相互「重疊」?

注:

  • 每個這條規則單獨工作

  • 當我使用第二個規則,然後http://example.com/someone/blah =>index.php?id=blah&user=someone作品,但似乎根文件夾不再是//someone/,然後找不到CSS ...在這種情況下如何防止基礎文件夾被更改?

回答

2

你有4個問題:

  1. 您的第一條規則(.*)將任何東西轉換成/index.php?id=$1
  2. 你的第二個規則不驗證,如果一個文件或文件夾是否存在,並可能陷入一個死循環導致500 internal server error
  3. 你的規則你使用相對路徑來服務CSS和圖像導致它失敗,您的網址格式
  4. 的順序,如domain.com/anything/anything

要解決這個問題,重定向,您可以使用這樣的:

<IfModule mod_rewrite.c> 
    RewriteEngine On 
    RewriteBase/

    RewriteRule ^index\.php$ - [L] 

    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^([^/]+)/([^/]+)$ /index.php?id=$2&user=$1 [L] 

    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^([^/]+)$ /index.php?id=$1 [L] 
</IfModule> 

因爲我已經改變了正則表達式(以([^/]+)這意味着什麼不是/),捕捉你想要的數據和命令在這種情況下都不會有問題,因爲它會具體匹配:

domain.com/anything 

而且

domain.com/anything/anything 

要解決的CSS和圖像您可以使用base TAG來定義你的絕對URL到您的HTML:

<base href="http://domain.com/"> 
+2

+1出色答卷具有很好的解釋 – anubhava 2014-10-08 16:50:03

+0

非常感謝你,現在對我來說更加清晰! – Basj 2014-10-08 19:07:04

+0

更一般的(這裏沒有具體說明),你將如何添加一個後備?即'如果所有列出的條件都不滿足,則轉到url /' – Basj 2014-10-08 20:04:45