2012-02-21 48 views
1

我想重定向所有嘗試訪問文件夾中的文件的URL到一個公共的PHP頁面,在那裏我登錄正在下載的文件,並檢查用戶是否登錄或沒有,我想下面這樣,但我沒有得到需要的結果htaccess選擇任何網址

方法1:

RewriteEngine on 
RewrteRule ^(.+)$ index.php?file=$1 

方法2:

RewriteEngine on 
RewriteRule ^([a-zA-Z0-9\-]+)$ index.php?file=$1 

我的index.php

<php echo 'file - ' . $_REQUEST['file']; ?> 

當我使用的URL作爲http://localhost/next/files/Cool 輸出方式1:

file - index.php 

輸出方法2:

file - Cool 

你能告訴我什麼是我做了錯誤的在方法1中。 我可以使用方法-2,但文件名可以是任何[可能包含的所有字符],所以我需要一個正則表達式,涵蓋了所有的[像方法1]

問候

回答

1
RewriteEngine on 
RewriteRule ^(.*)$ index.php?file=$1 [NC,L] 
+0

對不起,dint工作。 但是,這工作:[L,QSA]從http://stackoverflow.com/questions/5027388/htaccess-match-any-url-in-the-same-domain 請你讓我知道這是什麼? – user237865 2012-02-21 10:02:17

+1

在這裏你可以找到所有標誌解釋http://httpd.apache.org/docs/2.4/rewrite/flags.html – Vytautas 2012-02-21 10:20:36

1

問題與方法1是你創建一個無盡的重定向。 由於所有文件都被重定向到index.php,因此index.php本身也被重定向到index.php,等等。

你必須明確地排除重定向的index.php:

RewriteEngine on 
RewriteCond %{REQUEST_URI} !^/index.php 
RewriteRule ^(.+)$ /index.php?file=$1 
1

寫您的第一條規則是這樣的:

Options +FollowSymLinks -MultiViews 
# Turn mod_rewrite on 
RewriteEngine On 
RewriteBase/

# If the request is not for a valid file 
RewriteCond %{REQUEST_FILENAME} !-d 
# If the request is not for a valid directory 
RewriteCond %{REQUEST_FILENAME} !-f 
# forward requests to index.php as a query parameter 
RewriteRule ^(.*)$ index.php?file=$1 [QSA,L] 

和你的index.php讀取裏面file查詢參數爲:

echo 'file - ' . $_GET['file']; 
+0

這顯然不工作,因爲重寫應該專門重寫*現有的*文件index.php,也。 – apfelbox 2012-02-22 10:26:27

+0

謝謝,小問題什麼是fileName包含空間。說圖片(1).jpg然後它只匹配圖片(離開(1).jpg) - 這裏有任何建議。 – user237865 2012-02-22 10:56:31

+0

@apfelbox請開始閱讀關於mod_rewrite的內容,'RewriteCond%{REQUEST_FILENAME}!-f'將跳過任何物理文件的重寫規則。我的回答也有評論,但可能你沒有注意到他們。 – anubhava 2012-02-22 13:23:51