301 通过 .htaccess 将查询字符串重定向到 SEO 友好的 URL [英] 301 redirect query string to SEO friendly URLs through .htaccess

查看:17
本文介绍了301 通过 .htaccess 将查询字符串重定向到 SEO 友好的 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 .htaccess 文件中编写了一些代码,允许使用对 SEO 友好的 URL 而不是丑陋的查询字符串.以下代码将浏览器中的 SEO 友好版本重写为服务器上的查询字符串版本.

I’ve written some code on my .htaccess file which allows the use of SEO friendly URLs instead of ugly query strings. The following code rewrites the SEO friendly version in the browser to the query string version on the server.

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

所以丑

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

现在很漂亮

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

只是稍微解释一下代码;seo是在URL中添加更多关键字,/directory/是.htaccess文件所在的目录,参数size=large> 和 colour=green 永远不会改变,而 pattern=$1 可以是许多不同的值.

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.

以上代码完美运行.但是,问题是我现在被两个指向完全相同内容的 URL 卡住了.为了解决这个问题,我想 301 将旧的、丑陋的查询字符串重定向到 SEO 友好的 URL.到目前为止,我尝试过的方法不起作用 - 谷歌今天也不是特别友好.

The above code works perfectly. However, the problem is I am now stuck with two URLs that point to exactly the same content. To solve this, I would like to 301 redirect the old, ugly querystrings to the SEO friendly URLs. What I have tried so far does not work - and Google is not being particularly friendly today.

任何人都可以提供工作代码来放入我的 .htaccess 文件中,该文件将丑陋的重定向到新的 URL,同时保留重写?谢谢!

Can anybody offer working code to put in my .htaccess file that redirects ugly to new URL, while retaining the rewrite? Thanks!

推荐答案

这应该可以解决问题:

重写引擎开启

## 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]

如果需要,您还可以匹配大小和颜色,将它们也更改为正则表达式组,并使用相应的 %N

You can also match the size and colour if needed, by changing those to regex groups as well, and using the corresponding %N

希望这会有所帮助.

这篇关于301 通过 .htaccess 将查询字符串重定向到 SEO 友好的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆