Zergius2
Zergius2

Reputation: 124

URL rewrite (routing), mod_rewrite, or PHP

Was trying to sort it out by myself but no luck.

I have a website (PHP, Apache), with the following structure, as a sample:

1. http://hostname/ 
2. http://hostname/category?list=listname 
3. http://hostname/product?id=...&name=productname 
4. http://hostname/recipes 
5. http://hostname/recipe?id=...&name=recipename

+ many others.

Current .htaccess is:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php 

So for examples http://hostname/category?list=... becomes /category.php?list... And then it catches php script and works.

I want to make friendly URLs like these:

1. http://hostname/ 
2. http://hostname/category/listname/
3. http://hostname/product/productname/
4. http://hostname/recipes/
5. http://hostname/recipe/recipename/

And on the other hand previous urls must still work as webiste is hugely indexed by search enginges. So from oldstyle urls it must 301 redirect to new urls. Any ideas? All my efforts had errors. I even tried to make PHP routing via index.php entry point, but i cant get how to deal with oldstyle links.

Upvotes: 2

Views: 616

Answers (1)

hjpotter92
hjpotter92

Reputation: 80657

First, disable multiviews if it is enabled. Try the following rules to enable 301 redrects to new url structures:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^GET\ /(category|product|recipe)(?:\.php)?\?.*(name|list)=([^&\s]+) [NC]
RewriteRule ^ /%1/%3/? [R=301,L,NC]

As for the local/internal redirects back to actual pages, that'd have to be dealt with individually:

RewriteRule ^(category)/([^/]+)/?$ /$1.php?list=$2 [NC,L]
RewriteRule ^(recipe|product)/([^/]+)/?$ /$1.php?name=$2 [NC,L]
RewriteRule ^(recipe)/?$ /$1.php [NC,L]

Upvotes: 1

Related Questions