使用apache mod_rewrite创建SEO友好URL

时间:2015-06-09 13:06:12

标签: php regex apache .htaccess mod-rewrite

我正在尝试使用apache mod_rewrite将我丑陋的网址转换为SEO友好网址。

这就是我目前URL的样子:

index.php?p=search
index.php?p=contact
index.php?p=my-account&user=1
index.php?p=my-account&user=1

这是我对重写的期望:

mydomain.com/search
mydomain.com/contact
mydomain.com/my-account/1
mydomain.com/my-account/1

如果我通过我的网址传递了一个查询字符串。我可以在我的.htaccess文件中这样做。但是在URL中查询字符串多于一个时,不确定如何执行此操作。

# Create SEO friendly URL 
# Eg: index.php?p=search to domain/search
<ifModule mod_rewrite.c>

# Turn on the engine:
RewriteEngine on

# Redirect certain paths to index.php:
RewriteRule ^(search|contact)/?$ index.php?p=$1 

</ifModule>

如果URL有一个字符串,这是有效的。 任何人都可以告诉我如何为更多的查询字符串执行此操作。

谢谢。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

<ifModule mod_rewrite.c>

# Turn on the engine:
RewriteEngine on

# Redirect certain paths to index.php:
RewriteRule ^(search|contact)/?$ index.php?p=$1 [L,QSA,NC]

RewriteRule ^([\w-]+)/([\w-]+)/?$ index.php?p=$1&user=$2 [L,QSA,NC]

</ifModule>