How to redirect old “ugly” urls to seo-friendly on

2019-02-28 11:06发布

问题:

I'm new to mod_rewrite and need to do something for my client.

Suppose I have the www.mydomain.com/products.php?prod_id=32.

This product has a section (clothes) and a name (shirt). These names and sections are unique.

In a SEO-Friendly Url, it should be www.mydomain.com/products/clothes/shirt/.

I know I can create

RewriteRule ^products/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ products.php?section=$1&name=$2

I can do that, and it works. But I want people who enter www.mydomain.com/products.php?prod_id=32 to be redirected to www.mydomain.com/products/clothes/shirt/ (changed in the browser itself). How can I do that without inserting the id in my url? Is it possible to call a "pre-processing" php file in my .htaccess, and recreate "products.php?section=$1&name=$2"?

Anyone has a good link with really detailed explanation of mod_rewrite?

Thanks!

回答1:

You may have a bigger problem than mod_rewrite can handle gracefully. You can also use PHP to return a redirect to the browser. That way you can access your database to figure out that product_id 32 is /clothes/shirts/



回答2:

I see no other option than doing it inside PHP.

You can add something to the top of your products.php page that checks the URL ($_SERVER['REQUEST_URI']) to see if it contains products.php - If it does, redirect the person. You'll need to query your database to find out the product category and the name before redirecting though.

Remember to set the Moved Permanently header to improve SEO further :)



回答3:

This data might be passed by the browser via the "Referer" header field. You could progress that url and look at the get arguments. If I remember right, this isn't supported on all browsers.



回答4:

at the top of products.php (or any page you want to redirect) you could put a function call

redirectToSeoUrl();

Then in one of your include files write a redirectToSeoUrl function that gets the new url and redirects. Make sure to put the code before anything is output to the browser.



回答5:

Apache? Try an .htaccess redirect. No mod_rewrite needed.

Example: Redirect 301 /oldpage.html http://www.example.com/newpage.html