1

I have a MySQL database with 5000 items. The table is structured as

id
product-name
content
product-url

You can access a specific product page by going to www.site.com/products/index.php?id=123. The index.php file uses PHP to GET the ID to search the MySQL database and return the appropriate product name and content.

How can I make it so instead of www.site.com/products/index.php?id=123, the URL is rewritten or redirected to www.site.com/products/product-url? If I do it with .htaccess, will the index.php file still be able to know what ID to use to look up the product-url if the ID is not in the URL? Or is there some way to map URLs with PHP and MySQL?

(I'm a noob when it comes to this stuff, so any help will be much appreciated. Thanks.)

1 Answer 1

4

You can use .htaccess and a RewriteRule. The following will redirect an SEO URL to index.php with $_GET['product-url']. You will need to modify your code to either lookup the product id or use the product-url directly. Both should be unique in your products table.

RewriteEngine On
RewriteBase /

# redirect product page from SEO URL
RewriteRule ^products/([\w\d-_]+)/?$ products/index.php?product-url=$1 [L]

Note: I've made the product_url to only allow letters, numbers, dashes and underscores. I suggest such a restriction. In addition, the trailing slash is optional. Futhermore, this will not reappend a query string. If you need that you can add the QSA flag to the RewriteRule.

Sign up to request clarification or add additional context in comments.

2 Comments

I added a comment about periods in the product-url, but I just deleted the .php extension and now it works like a charm! Thanks so much.
I don't see your comment. You want periods in the product-url? I would advise against that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.