【问题标题】:How to write htaccess rewrite rule for seo friendly url如何为 seo 友好的 url 编写 htaccess 重写规则
【发布时间】:2015-03-25 22:38:40
【问题描述】:
  • 我是.htaccess 的新手。
  • 我需要一些 URLs 的重写规则。
  • 我在 Google 上搜索了一些并申请了,但 URL 没有变化。

我想要:

demo.example.com/section.php?id=1 

改为:

demo.example.com/section/sample-section

我试过了

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^section/(\d+)*$ ./section.php?id=$1

但没有区别

谢谢。

感谢您的帮助。

【问题讨论】:

标签: .htaccess mod-rewrite


【解决方案1】:

首先,确保 mod_rewrite 在您的 Apache 配置中启用并且 htaccess 文件允许

然后,将此代码放入您的 htaccess(必须在根文件夹中)

Options -MultiViews
RewriteEngine On

# redirect "/section.php?id=xxx" to "/section/xxx"
RewriteCond %{THE_REQUEST} \s/section\.php\?id=([0-9]+)\s [NC]
RewriteRule ^ /section/%1? [R=301,L]

# internally rewrite "/section/xxx" to "/section.php?id=xxx"
RewriteRule ^section/([0-9]+)$ /section.php?id=$1 [L]

【讨论】:

  • 卢曼谢谢。它工作得很好。我想问一件事。现在我必须相应地更改我的 php 代码。我的意思是必须排除并获得部分标题?
  • 其实你不需要改变任何东西,因为你仍然得到id参数“在后面”(隐藏)。我不确定我是否理解你的问题,如果不是这样,请解释
  • 是的,这就是我想知道的关于 id 的内容。但是在应用这个 htaccess 之后。收到 404 错误。
  • 您尝试的网址到底是什么?另外,请确保 mod_rewrite 已启用并且 htaccess 在您的 apache 配置中允许
【解决方案2】:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^section/([^/]+)$ /section.php?id=$1 [L]

这会将example.com/section.php?id=X 变成example.com/section/X

我建议将 URI 存储在数据库中,然后使用 section.php?uri=

例如:

example.com/section.php?uri=super-awesome

会变成:

example.com/section/super-awesome

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2023-03-24
    • 1970-01-01
    • 2015-06-30
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多