2016-11-27 52 views
1

我創建與我要實現三樣東西一個htaccess:htaccess的行爲不象預期

  • 刪除斜線
  • 重定向是不是所有的請求cssicojpgjsphppng文件到index.php
  • 重定向所有文件view.php如果查詢字符串開頭不是a

目前,它看起來像這樣

RewriteEngine On 
RewriteBase /test/ 
RewriteRule ^(.*)/$ $1 [N]         # remove trailing slash 

RewriteCond %{REQUEST_URI} !\.(css|ico|jpg|js|php|png)$  # if it isn't one of the files 
RewriteRule . "index.php" [L]        # then redirect to index 

RewriteCond %{QUERY_STRING} !^a($|&)      # if query doesn't start with a 
RewriteRule . "view.php" [L]        # then redirect to view 

這樣,下面的測試案例應該是真實的:

http://127.0.0.1/test/contact    ->   http://127.0.0.1/test/index.php 
http://127.0.0.1/test/contact/    ->   http://127.0.0.1/test/index.php 
http://127.0.0.1/test/contact.png   ->   http://127.0.0.1/test/view.php 
http://127.0.0.1/test/contact.png?a   ->   http://127.0.0.1/test/contact.png?a 

當我嘗試這些出來this site,它表明我到底這些結果。
然而在實踐中,當我嘗試的URL,它完全打破:

http://127.0.0.1/test/contact    ->   http://127.0.0.1/test/view.php 
http://127.0.0.1/test/contact/    ->   Error 500 
http://127.0.0.1/test/contact.png   ->   http://127.0.0.1/test/view.php 
http://127.0.0.1/test/contact.png?a   ->   http://127.0.0.1/test/contact.png?a 

看來,如果腳本總是在查詢相關的部分看起來第一,但考慮到這一點,但它仍然沒有按對我來說,/contact/休息時間沒什麼意義。當我刪除與查詢有關的部分時,其餘的工作。

我忘了什麼嗎?有沒有關於我不知道的操作順序的規則?我有打字錯誤嗎?

所有的輸入讚賞!

P.S.我知道我必須添加一個以a開頭的查詢,用於所有本地圖像,樣式表,腳本和AJAX調用。我這樣做是爲了當人們在單獨的標籤中查看媒體時,我可以創建一個花哨的頁面,讓人們瀏覽服務器上公開存在的所有媒體。

+0

你能啓用和發佈的調試日誌重寫模塊([RewriteLog和RewriteLogLevel(https://httpd.apache.org/docs /2.2/mod/mod_rewrite.html#rewritelog)for apache 2.2, [LogLevel](https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging)for apache 2.4)? –

回答

3

與您的代碼的問題:

  1. 首先非CSS/JS /圖像請求路由到index.php再沒有任何?a被路由到view.php所以最終index.php不會被使用在所有。對於任何沒有.php擴展名的內容,您需要在最後一條規則中使用否定條件。
  2. mod_rewrite語法不允許內嵌註釋。
  3. 您需要R第一條規則中的標誌來更改瀏覽器中的URL。

可以在/test/.htaccess使用此代碼:

RewriteEngine On 
RewriteBase /test/ 

# if not a directory then remove trailing slash 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.+)/$ $1 [L,NE,R=301] 

RewriteCond %{REQUEST_URI} !\.(css|ico|jpe?g|js|php|png)$ 
RewriteRule . index.php [L] 

RewriteCond %{QUERY_STRING} !(^|&)a [NC] 
RewriteRule !\.php$ view.php [L,NC] 
+0

它現在可以工作,但是在文件相關部分使用L標誌時,如何讀取與查詢有關的部分? –

+0

'L'標誌不會停止執行其他規則。它只是導致'mod_rewrite'循環再次運行。 (它在'while'循環中作爲'continue'而不是'break') – anubhava

+0

接受,因爲你完美地解決了這個問題。如果你不介意,我還有另外一個問題。將「R」標誌添加到尾部斜槓規則不會更新瀏覽器的URL。你知道爲什麼嗎? –