正则表达式,以避免“脏”的Web链接

时间:2011-08-29 23:26:16

标签: html regex .htaccess

如果这是我对文件的实际网址:

  

http://www.example.org/posts.php?post=example-post-name

在我的.htaccess文件中,如何在用户提交时使用正则表达式到达此路径:

  

http://www.example.org/posts/example-post-name

到目前为止,我已经提出了几个例子(这也包括一个www重定向):

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,L]

RewriteCond %{REQUEST_URI} !(\.[^./]+)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule (.*) /$1.php [L]
RewriteRule ^posts/([A-Za-z])/$ /posts.php?post=$1

但是我没有太多运气,有谁能告诉我哪里出错了?

3 个答案:

答案 0 :(得分:3)

您的+群组后需要A-Za-z来表示一个或多个字符,并且您还需要在该群组的末尾添加-。最后,/?表示最终斜杠可能存在,也可能不存在。

最后,添加[L]以确保不再处理其他重写规则。

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,L]

# First rewrite the posts:
RewriteRule ^posts/([A-Za-z-]+)/?$ /posts.php?post=$1 [L]

# ing0 edit: add in dirs that need changing back.
# (I dont know if there is an easier way to do this).
RewriteRule ^posts/css/(.*)$ /css/$1 [L]
RewriteRule ^posts/img/(.*)$ /img/$1 [L]
# etc

# Then, if it's not a real file and doesn't already end in .php
# Note change here ...
RewriteCond %{REQUEST_URI} !\.php$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# redirect it to PHP.
RewriteRule (.*) /$1.php [L]

答案 1 :(得分:0)

我认为你需要匹配整个网址并且正则表达式不太正确。试试这个:

RewriteRule ^(.*)/posts/([\w-]+)$ $1/posts.php?post=$2

如果只能匹配网址的非基本部分,请执行以下操作:

RewriteRule ^posts/([\w-]+)$ posts.php?post=$1

答案 2 :(得分:0)

为什么不使用:

RewriteRule ^posts/(.*)/$ posts.php?post=$1