在htaccess中重写规则以获得很好的链接,我需要建议

时间:2013-07-03 13:38:38

标签: regex .htaccess url-rewriting

我试图在我的应用中制作好的链接。

我决定重写看起来像这样的链接:

1. http://example.cz/get1/get2/get3
2. http://example.cz

进入这些(我只有php appliactions):

1. http://example.cz/index.php?path=get1+get2+get3
2. http://example.cz/index.php?path=

我在链接之前删除了www。

我一直未能将其重写为.htaccess

如果重写的主要想法得到params到path = get1 + get2 + get3是好的,我也在寻求建议吗?现在我可以看到像http://www.example.cz/you+me/这样的链接可能会在某处失败。你有更好的解决方案吗?

所以问题是:如何将其重写为.htaccess以及如何解决包含' +'

的链接可能出现的问题

修改

我提高了一点技能,我这样做了:

RewriteEngine on
Options +FollowSymlinks

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

RewriteCond %{REQUEST_URI} !^\/index.php(.*)
RewriteRule ^(.+) /index.php?path=/$1 [R=301,L] # 301 is here so I can see how does it work

# everything above works well (as I want)
# link now look like this one: 
# http://example.net/index.php?path=/get1/get2/get3
# Now I was looking for universal rule that will rewrite my get params...

# First I did this:
RewriteCond %{REQUEST_URI} /([^/]+) 
RewriteCond %1 !index.php(.*)
RewriteRule /([^/]+) $1+ [R=301,L]

# If any part of request uri is string that matches pattern /([^/]+) 
# And if ([^/]+) doesn't match index.php(.*)
# then rewrite every /([^/]+) into $1+
# Now I see that it is incorrect, but I wasn't able to fix it

# So then I did different rule
RewriteRule ^([^=]+=[^\/]*)\/([^\/]+)(.*)$ $1$2+$3 [R=301,L]

# start of string
# first var is: one or more chars except =, =, zero or more chars except /
# /
# second var is: one or more chars except /
# third var is: zero or more chars
# end of string

我认为第二个想法要好得多,但它也不起作用。请帮我修理一下。

2 个答案:

答案 0 :(得分:1)

您可以使用Apache模块mod_rewrite执行此操作。您可能已经安装了它。试试这个:

RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ index.php?path=$1+$2+$3 [L]

此正则表达式假定URL始终包含斜杠之间的三组文本。你可以根据需要调整它。

另请注意,Apache从不会看到URL哈希,因此您无法在重写规则中匹配它。幸运的是,看起来你不想对它做任何事情。只需使用上面的规则,哈希将保留在浏览器中URL的末尾。

答案 1 :(得分:0)

我做了解决方案。问题是在添加index.php之后?path =我无法使用查询字符串...

http://www.example.net/get1/get2/get3的链接转换为的最终通用解决方案 http://example.net/index.php?path=get1+get2+get3

RewriteEngine on
RewriteBase /
Options +FollowSymlinks

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

RewriteCond %{REQUEST_URI} !^\/index.php(.*)
RewriteRule ^(.+) /index.phppath=/$1 [R=301,L]

RewriteRule ^([^=]+=[^/]*)/([^/]+)(.*)$ $1$2+/$3 [R=301,L]
RewriteRule ^(.*)\+/+$ $1 [R=301,L]
RewriteRule ^(.*)path=(.*)$ $1?path=$2 [R=301,L]