开发者

URL rewriting with PHP MySQL .htaccess & GET

开发者 https://www.devze.com 2023-01-24 02:16 出处:网络
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开发者_StackOve

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开发者_StackOverflow.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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消