使用重写规则简化URL

时间:2015-11-29 10:01:15

标签: regex .htaccess url mod-rewrite rewrite

我的博客在categories.php页面中有许多类别。原始网址如下所示:

http://myname.com/articles.php?category=music

我简化为:

http://myname.com/articles/music

使用:

RewriteRule ^articles/([\w-]+)/?$       articles.php?cat=$1 [NC,L,QSA]

但有没有办法将其进一步简化为:

http://myname.com/music

-

更新:

我已经解决了原来的问题,但现在我遇到了另一个问题。我的.htaccess是:

Options -MultiViews

DirectoryIndex articles.php

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d    

RewriteRule ^([\w-]+)/?$                        articles.php?cat=$1 [NC,L,QSA]
RewriteRule ^([\w-]+)/([0-9]+)/?$               articles.php?cat=$1&currentpage=$2 [NC,L,QSA]
RewriteRule ^([0-9]+)/([\w-]+)/?$               article.php?id=$1&title=$2 [NC,L,QSA]

RewriteRule ^articles articles.php
RewriteRule ^categories categories.php
RewriteRule ^about about.php
RewriteRule ^feed feed.php
RewriteRule ^privacy privacy.php

当我访问http://myname.com/articleshttp://myname.com/article...时,一切正常,但当我转到http://myname.com/categorieshttp://myname.com/feed等时,我会重定向回主页。任何想法为什么会这样?

1 个答案:

答案 0 :(得分:0)

您可以在DOCUMENT_ROOT/.htaccess文件中使用此规则:

RewriteEngine On
RewriteBase /

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([\w-]+)/?$ articles.php?cat=$1 [L,QSA]