301 redirect query string to SEO friendly URLs thr

2019-02-20 12:10发布

问题:

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]

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.

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.

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

回答1:

This should do the trick:

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

Hope this helps.



回答2:

Not tested, but this may work...

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