Mod_rewrite检查php文件是否存在

时间:2013-10-27 13:46:20

标签: apache .htaccess mod-rewrite

我正在尝试编写一些mod_rewrite规则。目前一切正常。目前,我的通用网址如下所示:

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-us重定向到website.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]

如果您需要任何进一步的信息,请告诉我! 我很感谢回复:)

2 个答案:

答案 0 :(得分:11)

将您的.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]以使匹配不区分大小写。

答案 1 :(得分:2)

我会用这个:

#
# 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]