8

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

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

目前,这两个链接被 mod_rewritten to content.php,因为about-us并且privacy不作为 .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]

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

4

2 回答 2

13

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

我还为您的其他RewriteRules 简化了模式匹配。请注意使用[QSA]自动转发任何额外的查询参数[NC]并使匹配不区分大小写。

于 2013-10-27T14:00:14.843 回答
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]
于 2013-10-27T14:09:08.357 回答