使用 PHP MySQL .htaccess 进行 URL 重写得到

发布于 2024-10-01 15:09:53 字数 443 浏览 0 评论 0原文

我有一个包含 5000 个项目的 MySQL 数据库。该表的结构为

id
产品名称
内容
产品网址

您可以通过访问 www.site.com/products/index.php?id=123 来访问特定产品页面。 index.php 文件使用 PHP 获取 ID 来搜索 MySQL 数据库并返回相应的产品名称和内容。

我怎样才能使URL被重写或重定向到www.site.com/products/product-url而不是www.site.com/products/index.php?id=123?如果我使用 .htaccess 执行此操作,如果 ID 不在 URL 中,index.php 文件是否仍然能够知道使用哪个 ID 来查找产品 URL?或者有什么方法可以用 PHP 和 MySQL 映射 URL 吗?

(对于这些东西,我是个菜鸟,所以任何帮助将不胜感激。谢谢。)

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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

简单 2024-10-08 15:09:53

您可以使用 .htaccess 和 RewriteRule。以下代码将使用 $_GET['product-url'] 将 SEO URL 重定向到 index.php。您需要修改代码以查找产品 id 或直接使用 product-url。两者在您的产品表中都应该是唯一的。

RewriteEngine On
RewriteBase /

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

注意:我已将 product_url 设置为仅允许使用字母、数字、破折号和下划线。我建议这样的限制。此外,尾部斜杠是可选的。此外,这不会重新附加查询字符串。如果需要,可以将 QSA 标志添加到 RewriteRule 中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文