2013-10-27 137 views
7

我正在嘗試寫幾個mod_rewrite規則。目前一切正常。此刻我的通用網址看起來是這樣的:Mod_rewrite檢查php文件是否存在

http://website.com/about-us 
http://website.com/privacy 

目前,這兩個鏈接mod_rewritten到content.php,因爲about-usprivacy不存在爲.php文件,而是其內容存儲在一個數據庫,content.php檢索。

我有另外一個網址:

http://website.com/contact-us 

其中確實存在爲.php文件,因爲它包含自定義數據。 如何檢查contact-us.php是否存在。如果是這樣,重定向到website.com/contact-uswebsite.com/contact-us.php,否則,重定向到website.com/content.php

下面是我的mod_rewrite的文件,因爲它代表:

RewriteEngine On 

# I want the following condition and rule to look to see if the .php file exists, 
# and if it does, redirect to the physical page, otherwise, redirect to content.php 
RewriteCond %{DOCUMENT_ROOT}/([a-zA-Z0-9\-_]+).php -f 
RewriteRule ^([a-zA-Z0-9\-_]+)\.php$ [L] 


RewriteRule ^([a-zA-Z0-9\-_]+)$ /content.php [L] 
RewriteRule ^(product1|product2|product3)/(designer1|designer2|designer3)$ /search.php?productType=$1&designer=$2 [L] 
RewriteRule ^sale/(product1|product2|product3)$ /search.php?sale=1&productType=$1 [L] 

如果您需要任何進一步的信息,請讓我知道! 我很欣賞的答覆:)

回答

9

更改.htaccess代碼

RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-d # not an existing dir 
RewriteCond %{REQUEST_FILENAME} !-f # not an existing file 
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.php -f # and page.php exists 

# redirect to the physical page 
RewriteRule ^(.*)$ $1.php [L] 

# otherwise, redirect to content.php 
RewriteRule^/content.php [L] 

RewriteRule ^sale/(product[123])$ /search.php?sale=1&productType=$1 [QSA,NC,L] 
RewriteRule ^(product[123])/(designer[123])$ /search.php?productType=$1&designer=$2 [QSA,NC,L] 

我還簡化了您的其他RewriteRule小號匹配模式。請注意,使用[QSA]可自動轉發任何額外的查詢參數,並使用[NC]以使匹配不區分大小寫。

+0

感謝您的答覆,不幸的是,它的未來與一個500內部服務器錯誤:( –

+0

刪除'/'%之間'{DOCUMENT_ROOT}%{REQUEST_URI}' –

+0

還可以看看其他'RewriteRule'的簡單模式匹配 –

1

我這樣做:

# 
# redirect first the evidences: 
# 
RewriteRule ^(product1|product2|product3)/(designer1|designer2|designer3)$ /search.php? productType=$1&designer=$2 [L] 
RewriteRule ^sale/(product1|product2|product3)$ /search.php?sale=1&productType=$1 [L] 

# 
# redirect then the generality: 
# 
RewriteCond %{DOCUMENT_ROOT}%%{REQUEST_URI}.php -f 
RewriteRule^%{DOCUMENT_ROOT}%%{REQUEST_URI}.php [L] 

# 
# all other requests are rewritten to /content.php: 
# 
RewriteRule^/content.php [L]