简体   繁体   English

301通过.htaccess将查询字符串重定向到SEO友好URL

[英]301 redirect query string to SEO friendly URLs through .htaccess

I've written some code on my .htaccess file which allows the use of SEO friendly URLs instead of ugly query strings. 我在.htaccess文件上写了一些代码,它允许使用SEO友好的URL而不是丑陋的查询字符串。 The following code rewrites the SEO friendly version in the browser to the query string version on the server. 以下代码将浏览器中的SEO友好版本重写为服务器上的查询字符串版本。

RewriteEngine On
RewriteRule ^seo/([^/]*)/$ /directory/script.php?size=large&colour=green&pattern=$1 [L]

So that the ugly 这样丑陋

http://www.mysite.com/directory/script.php?size=large&colour=green&pattern=striped

Is now beautiful 现在很美

http://www.mysite.com/directory/seo/striped/

Just to explain the code a bit; 只是为了解释一下代码; seo is there to add more keywords to the URL, /directory/ is the directory in which the .htaccess file is located, parameters size=large and colour=green never change, while pattern=$1 can be many different values. seo用于向URL添加更多关键字, /directory/是.htaccess文件所在的目录,参数size=largecolour=green永远不会更改,而pattern=$1可以是许多不同的值。

The above code works perfectly. 上面的代码完美无缺。 However, the problem is I am now stuck with two URLs that point to exactly the same content. 但是,问题是我现在卡在两个指向完全相同内容的URL中。 To solve this, I would like to 301 redirect the old, ugly querystrings to the SEO friendly URLs. 为了解决这个问题,我想将旧的,丑陋的查询字符串重定向到SEO友好URL。 What I have tried so far does not work - and Google is not being particularly friendly today. 到目前为止我所尝试的并不起作用 - 谷歌今天并不是特别友好。

Can anybody offer working code to put in my .htaccess file that redirects ugly to new URL, while retaining the rewrite? 任何人都可以提供工作代码来放入我的.htaccess文件,将丑陋的重定向到新的URL,同时保留重写? Thanks! 谢谢!

This should do the trick: 这应该做的伎俩:

RewriteEngine On RewriteEngine On

## Redirect to pretty urls
# The '%1' in the rewrite comes from the group in the previous RewriteCond
RewriteCond %{REQUEST_URI} !seo
RewriteCond %{QUERY_STRING} ^size=large&colour=green&pattern=([a-zA-Z]*)$
RewriteRule (.*) /directory\/seo\/%1\/? [L,R=301]

## Rewrite to long url, additional parameter at the end will cause
## the internal redirect not to match the previous rule (would cause redirect loop)
RewriteRule ^directory\/seo\/([^/]*)/$ /directory/script.php? size=large&colour=green&pattern=$1&rewrite [L]

You can also match the size and colour if needed, by changing those to regex groups as well, and using the corresponding %N 如果需要,您还可以匹配大小和颜色,也可以将它们更改为正则表达式组,并使用相应的%N

Hope this helps. 希望这可以帮助。

Not tested, but this may work... 未经测试,但这可能有效......

RewriteRule ^directory/script.php?size=large&colour=green&pattern=(.*)$ /seo/$1/? RewriteRule ^目录/ script.php?size = large&color = green&pattern =(。*)$ / seo / $ 1 /? [R=301,NE,NC,L] [R = 301,NE,NC,L]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM