mod重写 - 第二条规则不起作用

时间:2011-12-04 08:40:15

标签: php mod-rewrite

我正在尝试学习网址重写。

我的代码:

RewriteEngine on    
RewriteRule ^/$ /index.php
RewriteRule ^/([a-z]+)$ /index.php?page=$1

当我这样尝试时:localhost/mysite它会显示主页。但是当我尝试这样的事情:localhost/mysite/abcdefg时,它会显示404错误。

修改 我想做的是: 如果只给出原始域,则应该转到主页。例如:www.mysite.com - > www.mysite.com/index.php。否则,如果www.mysite.com/contactus - > www.mysite.com/index.php?page=contactus

修改 我在Windows XP中使用WAMP服务器。

5 个答案:

答案 0 :(得分:1)

那是因为第一个规则会捕获第二个请求。现在,我仔细研究了正则表达式,不会没有抓住请求。但是,您的第二个请求将失败。此外,根据经验,重写越专业,它应该被放置得越高。

您无需重写所有索引请求,但如果您知道自己在做什么,请重新排序重写。

RewriteEngine on    
RewriteRule ^/([^/]+)/$ index.php?page=$1 [L]
RewriteRule ^/$ index.php [L]

编辑1 :考虑到您正在使用本地主机,这对您有用。

RewriteEngine on
RewriteBase /mysite/
RewriteRule ^([^/]+)/?$ mysite/index.php?page=$1 [L]
RewriteRule ^$ mysite/index.php [L]

当您上线时,只需删除mysite/部分。

注意:如果您访问RewriteRule ^$ /index.php [L],则不需要此规则index.php服务器将自动加载localhost/mysite。如果您的服务器配置为在index.php配置文件上加载默认页面httpd.conf,那么这是预期的行为。


编辑2 :我看到了您的编辑,但您无法在localhost中的当前网址结构中测试该重写。您应该尝试设置虚拟主机,以便在尽可能类似于您的产品的环境中进行测试。在Google上搜索如何为您的WAMP,XAMPP或您正在使用的任何其他堆栈创建虚拟主机。

然后重写规则很简单

RewriteEngine on
# page-url -> index.php?page=page-url
RewriteRule ^([^/]+)/?$ index.php?page=$1 [L]

答案 1 :(得分:0)

/localhost/mysite/abcdefg与您希望匹配的规则不匹配,因为路径(/mysite/abcdefg)中间包含/,与正则表达式不匹配。因此,Web服务器查找该文件,找不到它,并返回404。

答案 2 :(得分:0)

RewriteRule ^/([a-z]+)$ /index.php?page=$1

将匹配以/开头的任意字符串,后跟任意数量的字符a-z/不在此范围内,这就是/mysite/abcdefg失败的原因。

答案 3 :(得分:0)

@trott和@anders_lindahl是对的:

您的第一个匹配localhost/也就是网站的根目录。

第二个规则将匹配第一个斜杠后面的小写字母(以及那个!),localhost/thisisavalidstring

您已在其中放置/,因此无法匹配。使用类似的东西:

RewriteRule ^/([a-z\/]+)$ /index.php?page=$1

(没试过,但我认为它会起作用。我不太确定需要在[]内逃跑

答案 4 :(得分:0)

您可能打算使用

RewriteRule ^/([a-z/]+)$ /index.php?page=$1

RewriteRule ^/([a-z/]*/)?([a-z]+)$ /index.php?page=$2